Skip to content

← Algorithms and programming

From Blocks to Python

Unit 1 · Algorithms and programming

Hide the stories, facts, photos, activities and interactives, for revising before an exam
In this unit 11 sections
  1. From blocks to typed words
  2. Your first program: print
  3. Variables
  4. Four types of value
  5. Arithmetic
  6. Input: asking the user
  7. Reading error messages
  8. Blocks and Python side by side
  9. Plan, then type
  10. In short
  11. Exercise

In Grade 7 you built a tea-shop bill, a bus fare and a quiz by snapping blocks together. They asked questions, remembered the answers in variables, worked things out and chose what to say. The apps on your phone do the same things, but nobody built them from blocks. The people who wrote them typed every instruction, one line after another.

In this unit you start typing programs too, in a language called Python. You won’t learn new ideas first: a variable is still a variable, and asking is still asking. What is new is the way of writing them. By the end you will write programs that print, remember, calculate and ask, you will read Python’s error messages the way a mechanic reads a warning light, and you will turn any short block program from Grade 7 into Python.

From blocks to typed words

Blocks were a good way to start. You couldn’t misspell a block, and blocks that didn’t fit wouldn’t snap. But blocks get slow when a program grows to hundreds or thousands of instructions: there is a lot of dragging, and a big program no longer fits on the screen. So programmers mostly use a text-based language: the program is typed, like a message.

Python is a text-based programming language. A program written in Python is plain text: you can type it on a phone, send it in a message, or print it on paper. To run it, the computer needs a Python interpreter, a program that reads your Python one line at a time, from the top, and carries out each line. People all over the world use Python, from students writing their first program to scientists studying the weather and engineers building websites.

Here is the tea-shop bill from Grade 7, once as blocks and once as Python. You don’t need to understand every part of the Python yet; by the end of the unit you will.

Try it

The tea shop’s bill, two ways

Tap a block to see the line of Python that does the same job, and what is different. Then press Run under the Python and be the customer.

Blocks

ask … and keep the answer in name becomes name = input(…). The = puts the answer into the variable name.

Python

name = input("What is your name? ")cups = int(input("How many cups of tea? "))bill = cups * 30print(f"{name}, please pay Rs {bill}")

Look at what stayed the same: the same two questions, the same variables (name, cups, bill), the same calculation, in the same order. A block program and a Python program can say exactly the same thing. Only the way of writing it changed.

Running Python on this page

Every Python program in these pages has a Run button under it. Press it, and the program runs here on the page, on a phone or a computer, with nothing to install. What it prints appears under it, in a box like a computer’s screen. When a program asks a question, type your answer in that box and press Enter.

One thing works differently here. Python on a computer waits while you type an answer. This page can’t make Python wait, so it stops the program at the question, and when you press Enter it runs the program again from the first line, with all your answers so far typed in for you. For the programs in this book you won’t see the difference, except perhaps a short flicker after each answer.

Press Edit to change the program: tap where you want to type, as in a message. Press Run again to run your version, and Reset to get the book’s program back. Change things, break things and see what happens. You can’t harm anything: the program runs only inside this page.

The first time you press Run, the page downloads Python itself, about 6 MB, a little less than a short video. After that it comes from your browser’s memory, so later runs start quickly and use almost no data. Python needs the internet that first time, so press Run once while you have Wi-Fi.

Grace Hopper, seated, with three colleagues at the control console of a large early computer covered in switches and lights
Figure 1.1 Grace Hopper (seated) with three men from her programming department at Remington Rand, at a UNIVAC computer’s console. The Smithsonian dates the photo to 1957, while her team was building FLOW-MATIC. Photo: Smithsonian Institution, via Public.Resource.Org, CC BY 2.0

What does a Python interpreter do?

Pick an answer to see why.

Your first program: print

In blocks, say showed something in the output box. In Python, print does it. Press Run:

print("Namaste!")print("Welcome to Python.")

Output

Namaste!Welcome to Python.

Each print shows one line, in order from the top. Every part of a line matters:

  • print is written in small letters.
  • The round brackets ( ) hold what is to be printed.
  • The text inside the double quotes " " is printed exactly as it is, spaces and all. The quotes themselves are not printed: they only mark where the text starts and stops. Single quotes, 'Namaste!', work too, as long as both ends match.

Numbers are printed without quotes, and Python works out a sum before printing it:

print(5 + 3)print("5 + 3")

Output

85 + 3

Without quotes, 5 + 3 is a sum, and Python prints its answer. With quotes, it is just text, three characters with spaces between them, and Python prints it as it is.

To print several things on one line, separate them with commas. Python puts a space between them:

print("Cups of tea:", 4)print("Price per cup: Rs", 30)print()print("Thank you!")

Output

Cups of tea: 4Price per cup: Rs 30 Thank you!

print() with nothing inside prints an empty line.

Comments

A line, or the end of a line, that starts with # is a comment: a note for people reading the program. Python skips it.

# My first program, by Ashaprint("Namaste!")   # greet the user

Output

Namaste!

Comments say what a program is for, or why a line is there. They are useful in your own programs, and even more in someone else’s.

What does print("7 × 6") show?

Pick an answer to see why.

What does print("Bhaktapur", 2026) show?

Pick an answer to see why.

Variables

In Grade 7, set score to 0 put 0 into the variable score. In Python you write:

score = 0

Read = as “is set to”, or “gets”: score gets 0. It is not the equals of a math lesson. In math, x = 5 says that two things are equal; in Python, score = 0 is an instruction: put the value on the right into the variable on the left. Python makes the variable the first time you set it, so there is no Make a variable button.

To use a variable’s value, write its name, without quotes:

runs = 4print(runs)print("runs")

Output

4runs

print(runs) looks in the variable and prints what it holds. print("runs") prints the word runs.

Change by

There is no change block in Python. To add 6 to runs, you write:

runs = runs + 6

That would be nonsense in math, but read it as Python does, right side first: take the value in runs, add 6, and put the answer back into runs. If runs held 4, it now holds 10. Here is Grade 7’s cricket scorer:

runs = 0runs = runs + 4runs = runs + 6runs = runs + 1print("Runs:", runs)

Output

Runs: 11

Python also has a short way to write the same thing: runs += 6 means runs = runs + 6, and lives -= 1 means lives = lives - 1. You will see both in programs.

Naming variables

The rules for names are strict:

  • A name is made of letters, digits and the underscore _, with no spaces. Write bus_fare, not bus fare.
  • It can’t start with a digit: cups2 is fine, 2cups is not.
  • Capital letters matter: score, Score and SCORE are three different variables.
  • A few words are Python’s own, called keywords, and can’t be names: if, else, and, or, not, True, False, class, for, while and some others.

Choose names that say what is inside, as in Grade 7. Python programmers write names in small letters, with _ between the words: price_per_cup, total_marks.

lives holds 3. What does it hold after lives = lives - 1?

Pick an answer to see why.

Which of these can be a variable’s name in Python?

Pick an answer to see why.

Four types of value

In Grade 7 values came in three types: numbers, text and true/false. Python has the same three, but it splits numbers in two, so there are four:

Type Python’s name Examples What it is
whole number int (an integer) 12, 0, -30, 77 a number with no decimal point
decimal number float (a floating-point number) 7.5, 0.25, -1.0, 12.0 a number with a decimal point
text str (a string) "Sita", "Bhaktapur", "12", "" characters in quotes
true or false bool (a Boolean) True, False one of the two

A few things decide the type, and they are worth remembering:

  • Quotes make a string. 12 is an int, but "12" is a string: two characters, the digit 1 and the digit 2. "True" with quotes is a string too.
  • A decimal point makes a float. 12.0 is a float, even though it is a whole number.
  • True and False start with a capital letter, and have no quotes. true is not a value in Python: Python looks for a variable called true and doesn’t find one.
  • "" is a string with nothing in it, the empty string. It is still a string.

To ask Python a value’s type, use type():

print(type(77))print(type(7.5))print(type("77"))print(type(True))

Output

<class 'int'><class 'float'><class 'str'><class 'bool'>

Try it

Which type?

Each card is a value as it would be written in a Python program. Tap its type.

42

Which type is this value?

Tap a group above.

Card
1 of 14
Right the first time
0

Comparisons make True or False

A comparison works out to True or False, a bool, just as conditions did in Grade 7. Python has six comparison operators. A keyboard has no ≤, ≥ or ≠ keys, so three of them are written with two characters:

Python Means marks = 40
marks == 40 is equal to True
marks != 40 is not equal to False
marks < 40 is less than False
marks > 40 is more than False
marks <= 40 is less than or equal to True
marks >= 40 is more than or equal to True

With >= the rule “40 or more” is simply marks >= 40; you don’t need Grade 7’s trick of writing > 39.

Grade 7’s and, or and not are Python’s and, or and not, written small, and they work just the same:

age = 13grade = 8print(age >= 13)print(grade > 5 and grade < 9)print(not grade == 8)paid = Falseprint(paid)

Output

TrueTrueFalseFalse

Which value is a float?

Pick an answer to see why.

x = 7. What is the value of x != 7?

Pick an answer to see why.

Arithmetic

Python is a very good calculator. A keyboard has no × or ÷ keys, so multiplying is * (a star) and dividing is /:

Operator Does Example Answer
+ add 17 + 5 22
- take away 17 - 5 12
* multiply 17 * 5 85
/ divide 17 / 5 3.4
// divide, keeping only the whole number 17 // 5 3
% the remainder after dividing 17 % 5 2
** to the power of 2 ** 5 32

Two of these need a closer look.

/ always gives a float, even when the answer is whole: 6 / 2 is 3.0, not 3.

// and % are the two halves of the division you learned in primary school, where 17 ÷ 5 = 3 remainder 2. // (integer division) gives the 3, and % (the remainder, also called modulo) gives the 2. (% has nothing to do with percent in Python.) They are more useful than they look: anything that is shared out, packed, or counted in groups needs them.

Try it

Sharing momos

A plate of momos is shared out equally among friends, whole momos only. Change the number of momos and of friends, and watch // and %.

12345friendsleftover
17 / 5
3.4
17 // 5
3
17 % 5
2

Each friend gets 3 (that is //), and 2 are left over (that is %). Check: 5 × 3 + 2 = 17.

Which comes first?

Python works out a sum in the same order as in your math lessons: powers first, then multiplying and dividing (*, /, //, %), then adding and taking away, from left to right. Brackets come before everything, so use them when you want a different order, or just to make the order clear.

print(7 + 3 * 2)print((7 + 3) * 2)

Output

1320

A packet holds 6 eggs. How many full packets can 45 eggs fill?

Pick an answer to see why.

Input: asking the user

Grade 7’s ask … and keep the answer in … is Python’s input(). It shows the question, waits for the user to type an answer and press Enter, and gives back what they typed, which = keeps in a variable:

name = input("What is your name? ")print("Namaste,", name)

Output

What is your name? PembaNamaste, Pemba

In this book an output with an input shows the question and what the user typed on the same line, as the screen shows it. The space at the end of the question keeps the answer from sticking to the question mark.

input() always gives a string

Here is a careful-looking tea-shop bill. Run it and buy 2 cups:

cups = input("How many cups of tea? ")bill = cups * 30print("Please pay Rs", bill)

Output

How many cups of tea? 2Please pay Rs 222222222222222222222222222222

Python didn’t multiply 2 by 30. input() always gives a string, whatever is typed, because what you type are characters. So cups holds "2", the text, and "2" * 30 means “the text "2", thirty times”. There is no error message; the program just gives the wrong answer, which is the worst kind of bug.

Grade 7’s blocks quietly turned an answer that looked like a number into a number. Python doesn’t guess: you tell it. These functions convert a value from one type to another:

Function Turns into Example Answer
int() an int int("2") 2
float() a float float("2.5") 2.5
str() a string str(60) "60"

Put int() round input(), and the answer is turned into a whole number as soon as it is typed:

cups = int(input("How many cups of tea? "))bill = cups * 30print("Please pay Rs", bill)

Output

How many cups of tea? 2Please pay Rs 60

Read int(input("How many cups of tea? ")) from the inside out: input() asks and gives back the string "2", then int() turns "2" into the number 2. Use float() instead of int() when the answer can have a decimal point, such as a weight in kilograms or a price in rupees and paisa.

Putting values into text

The bill should say Please pay Rs 60., with a period right after the number. With a comma, print adds a space we don’t want. There are two other ways.

Join strings with +, as Grade 7’s join did. Both sides must be strings, so a number is turned into one with str() first:

bill = 60print("Please pay Rs " + str(bill) + ".")

Output

Please pay Rs 60.

Or, more neatly, an f-string: put f just before the opening quote, and write each value’s name in curly brackets { } where it should go. Python fills them in:

name = "Pemba"bill = 60print(f"{name}, please pay Rs {bill}.")

Output

Pemba, please pay Rs 60.

An f-string turns the values into text by itself, so there is no str() to forget. Most Python programmers use f-strings for messages like this.

age = input("How old are you? ") and the user types 13. What is in age?

Pick an answer to see why.

Reading error messages

Sooner or later, your programs will stop with an error message. That is normal: professional programmers see them every day. The difference between a beginner and a programmer is that the programmer reads the message. Python is telling you where it stopped and why, and usually that is enough to fix it in a minute.

Here is the tea-shop bill with a mistake, and the message Python gives:

cups = 2bill = cups * 30print("Please pay Rs " + bill)
12345Traceback (most recent call last):File "main.py", line 3, in <module>print("Please pay Rs " + bill)~~~~~~~~~~~~~~~~~^~~~~~TypeError: can only concatenate str (not "int") to str1the file and line number2the line it was running3the part that went wrong4the kind of error5what went wrong 123455Traceback (most recent call last):File "main.py", line 3, in <module>print("Please pay Rs " + bill)~~~~~~~~~~~~~~~~~^~~~~~TypeError: can only concatenate str(not "int") to str1the file and line number2the line it was running3the part that went wrong4the kind of error5what went wrong
Figure 1.2 The parts of an error message. Read the last line first: the kind of error and what went wrong. Then go to the line it names.

Read an error message in this order:

  1. The last line: the kind of error, then a colon, then what went wrong in Python’s words. Here, a TypeError: text can only be joined to text, and bill holds an int.
  2. The line number above it: where Python was when it stopped, line 3 here, and that line printed under it. The marks under the line (~~~^~~~ or ^^^) point at the part that went wrong.
  3. Fix one thing and run again. Here, print("Please pay Rs " + str(bill)), or an f-string.

Five errors you will meet

Error What it means A line that causes it
SyntaxError Python can’t read the line: it isn’t written the way Python is written (a missing quote, bracket or colon) print("Namaste)
IndentationError the spaces at the start of a line are wrong print("Hi") (two spaces before it)
NameError Python doesn’t know a name: misspelled, or used before it was set pirnt("Hi")
TypeError a value of the wrong type for this job "Rs " + 60
ValueError the right type, but a value that can’t be used int("two")

Python finds a SyntaxError or an IndentationError before it runs anything, so nothing at all is printed. The other three happen while the program runs, when Python reaches the line, so the lines before it have already done their work.

Each program below has one mistake. Press Run, read the message, then press Edit, fix it and run it again until it works. Try each one before you open its answer.

Try it

Read the error

For each program, read Python’s message. Tap the line it names, then say what kind of error it is, then choose the fix.

What Python says

  File "main.py", line 2
    print("Namaste, + name)
          ^
SyntaxError: unterminated string literal (detected at line 2)

1. Which line does the message name? Tap it in the program.

Read the message from the bottom up: the last line says what went wrong, the line above it where.

Program 1 of 6 · right the first time: 0 of 18

Blocks and Python side by side

Now you can read and write every block from Grade 7’s first programs in Python. Here they are, side by side:

Block Python
when ▶ Run is pressed nothing: a program runs from its first line
say “Hello” print("Hello")
set score to 0 score = 0
change score by 1 score = score + 1
ask “How old are you?” and keep the answer in age age = int(input("How old are you? ")) (or input() alone for text)
join “Runs: ” runs "Runs: " + str(runs), or f"Runs: {runs}"
cups × 30, total ÷ 4 cups * 30, total / 4
age = 12 (compare) age == 12
true, false True, False
and, or, not and, or, not
if … then … else … if …: and else:, with the lines inside indented

The mouth of an if is an indent

An if block had a mouth, and the blocks inside it ran only when the condition was true. Python has no mouths; it uses indentation: the lines inside an if start four spaces further right. The if line ends with a colon :, which says “the indented lines under me belong to me”, and so does else:. When the lines go back to the left edge, the if is over. Here is Grade 7’s bus fare:

Try it

The bus fare, two ways

Tap the if block, then the else. Which lines of Python are inside each? Run it three times: as a 3-year-old, a 4-year-old and a 5-year-old.

Blocks

The age must be a number to compare it with 5, so int( ) goes round input(). Without it, age < 5 compares text with a number, and Python stops with a TypeError, as the blocks stopped at “four” < 5.

Python

age = int(input("How old are you? "))if age < 5:    fare = 0else:    fare = 30print("Your fare is Rs", fare)

Because the spaces mean something, they must be exact. A missing colon is a SyntaxError (expected ':'), and a line that should be inside but isn’t indented is an IndentationError (expected an indented block after 'if' statement). In this book’s editor, press Enter after a line ending in a colon, and the next line starts four spaces in by itself.

Try it

Errors in an if

Two programs with an if, each with one mistake. Read the message, tap the line, name the error, choose the fix.

What Python says

  File "main.py", line 3
    fare = 0
    ^^^^
IndentationError: expected an indented block after 'if' statement on line 2

1. Which line does the message name? Tap it in the program.

Read the message from the bottom up: the last line says what went wrong, the line above it where.

Program 1 of 2 · right the first time: 0 of 6

You will learn much more about if and else, and about loops, in Unit 2. For now it is enough to read them, and to turn a block program into Python.

The quiz

Here is the first question of Grade 7’s quiz. Notice the ==, and what it means for the answer kathmandu with a small k.

Try it

The quiz, two ways

Tap each block to see its Python. Then run the Python and answer kathmandu, in small letters. Is it marked right? Why not?

Blocks

set score to 0 becomes score = 0.

Python

score = 0answer = input("What is the capital of Nepal? ")if answer == "Kathmandu":    print("Correct!")    score = score + 1else:    print("Sorry, the answer is Kathmandu.")print("Your score:", score)
Answer

Which Python line does the same as the block change lives by -1?

Pick an answer to see why.

Plan, then type

A typed program goes wrong in more ways than a block program, so plan it before you type, as you did in Grade 7:

  1. Say what it does, in a sentence: what it asks, what it works out, what it prints.
  2. List the variables, each with its type: which are ints, floats, strings, bools? Every number that comes from input() needs int() or float().
  3. Write the steps in plain words, then turn each into a line of Python.
  4. Type a little, run it, then type more. Run the program after every two or three lines. A mistake found in a three-line program takes seconds to fix; in a thirty-line one, much longer.
  5. Test it with answers you can check in your head, and with an awkward one: 0, a large number, a decimal.

In short

Exercise

What does print("10" + "5") show?

Pick an answer to see why.

Which line has a mistake?

Pick an answer to see why.

What is 23 % 4?

Pick an answer to see why.

A program stops with ValueError: invalid literal for int() with base 10: '12.5'. What happened?

Pick an answer to see why.

What type is the value of 7 / 7?

Pick an answer to see why.

In an error message, where do you find the kind of error?

Pick an answer to see why.

a.

Name Python’s four types of value from this unit, with two examples of each.

Answer
b.

What is the value of each expression? i. 9 + 6 / 3 ii. (9 + 6) / 3 iii. 2 ** 3 * 2 iv. 50 // 8 v. 50 % 8 vi. "ab" * 3

Answer
c.

What is the difference between = and == in Python? Give an example of each.

Answer
d.

Write the output of this program.

a = 5b = 2a = a + bb = a * bprint(a, b)print(a // b, a % b)print(f"{a} and {b}")
Answer
e.

Why does this program print 333 instead of 9? Correct it.

n = input("Pick a number: ")print(n * 3)

(The user typed 3.)

Answer
f.

Each line below stops with an error. Name the kind of error, and correct the line.

  • i.print("Namaste)
  • ii.total = 5 + "5"
  • iii.Print(10)
  • iv.x = int("ten")
  • v.print(price) (no variable price was set)
Answer
g.

Write a program that asks how many students are going on a trip, and prints how many 40-seat buses are completely full, and how many students are in the last bus. Test it with 130.

Answer
h.

Rewrite this block program in Python, and give its output when the user types 4.

when ▶ Run is pressedset price to 30ask “How many plates of momo?” and keep the answer in platesset bill to plates × pricechange bill by 20say join “Total with the delivery charge: Rs ” bill
Answer
i.

A student wrote this program to find the average of three marks, but it prints the wrong answer. Find the mistake, explain it, and correct it.

a = 60b = 70c = 80average = a + b + c / 3print(average)
Answer
j.

Explain how you read a Python error message, using this one as an example.

Error message

Traceback (most recent call last):  File "main.py", line 4, in <module>    total = pens * price            ^^^^NameError: name 'pens' is not defined
Answer