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.
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.
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:
printis 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 + 3Without 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 userOutput
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 = 0Read = 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
4runsprint(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 + 6That 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: 11Python 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. Writebus_fare, notbus fare. - It can’t start with a digit:
cups2is fine,2cupsis not. - Capital letters matter:
score,ScoreandSCOREare 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,whileand 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.
12is 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.0is a float, even though it is a whole number. TrueandFalsestart with a capital letter, and have no quotes.trueis not a value in Python: Python looks for a variable calledtrueand 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'>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
TrueTrueFalseFalseWhich 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.
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
1320A 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, PembaIn 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 222222222222222222222222222222Python 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 60Read 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)Read an error message in this order:
- 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.
- 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. - 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.
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:
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.
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.
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:
- Say what it does, in a sentence: what it asks, what it works out, what it prints.
- List the variables, each with its type: which are ints, floats, strings, bools? Every number that comes from
input()needsint()orfloat(). - Write the steps in plain words, then turn each into a line of Python.
- 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.
- 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.
Name Python’s four types of value from this unit, with two examples of each.
Answer
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
What is the difference between = and == in Python? Give an example of each.
Answer
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
Why does this program print 333 instead of 9? Correct it.
n = input("Pick a number: ")print(n * 3)(The user typed 3.)
Answer
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
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
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 ” billAnswer
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
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 definedAnswer
Quiz yourself: Algorithms and programming, Grades 6–12 →
Practice every question in the book, and keep track of the ones you miss →
