In Chapter 0 you ran a one-line program. In this chapter we slow right down and look at that line through a magnifying glass. By the end you will understand every character of it, know how to print almost anything, and — just as importantly — know what to do when Python tells you something went wrong.
Create a new file called first.py in your book folder, and type each example into it as you go. Run it after every change.
1.1 Hello, World
For decades, the first program people write in any new language has been one that displays the words Hello, World. In Python it is a single line:
print("Hello, World!")
Output
Hello, World!
Small as it is, this line contains four separate ideas. Let's take it apart.
print ( "Hello, World!" )
│ │ │ │
│ │ │ └─ closing bracket: end of the call
│ │ └─ the value we give to print: a piece of text
│ └─ opening bracket: "run print with the following..."
└─ the name of a function
print is a function. A function is a named, ready-made piece of code that does one job. print's job is to show things on the screen. Python comes with dozens of these built-in functions, and later you will write your own → Chapter 19.
The brackets ( ) call the function. Writing a function's name followed by brackets means "run this function now". Programmers say you are calling the function. Without the brackets, nothing runs — you are only mentioning its name.
What goes inside the brackets is the argument. An argument is a value you hand to the function for it to work with. Here, we hand print the text we want displayed.
The quotes make it text."Hello, World!" is a string: a piece of text. The quotation marks tell Python where the text starts and ends. They are not part of the text itself, which is why the output shows Hello, World! without quotes.
Put together, the line reads: "Call the function print, giving it the text Hello, World!."
Practice 1.1
Multiple choice
In print("Good morning"), what is the name for the value inside the brackets?
print is the function. The brackets call it.
The value that you hand to a function has its own name.
The answer is: The argument
An argument is a value you hand to a function. Here the argument is the text that print shows.
Fill in the blank
Fill in the name of the function that shows things on the screen.
("Hello, Tokyo!")
The finished program prints:
Target
Hello, Tokyo!
The name is written in lowercase letters.
It is the same function as in the Hello, World program.
print("Hello, Tokyo!")
print is the built-in function that shows its argument on the screen. The brackets after the name call it.
1.2 Printing text
Single or double quotes
Python accepts text in single quotes or double quotes. These two lines do exactly the same thing:
print("I love Python")print('I love Python')
Output
I love Python
I love Python
Pick one style and stay consistent. This book uses double quotes, which is the most common choice in professional Python code.
The quote at the start and the quote at the end must match. Mixing them is an error:
print("I love Python')
Output
File "first.py", line 1
print("I love Python')
^
SyntaxError: unterminated string literal (detected at line 1)
Python saw a ", started reading text, and kept looking for the matching " to end it. It reached the end of the line without finding one. "Unterminated string literal" means exactly that: a piece of text that never ends. You'll learn to read messages like this in section 1.8.
Quotes inside text
Having two styles is handy when your text itself contains a quote mark. Use the other kind on the outside:
print("It's raining")print('She said "hello" to me')
Output
It's raining
She said "hello" to me
There is also a way to put any quote inside any string using a backslash, called an escape sequence → Chapter 7.
Each print starts a new line
Every call to print finishes by moving to a new line. So several print lines produce several lines of output, in order:
"=" * 30 means "the text = repeated 30 times". You'll see why this works when we study string operations → Chapter 7.
Practice 1.2
Predict the output
What does it print?
print("It's late")print('Leo said "hi"')print("="*6)
The outside quotes mark where the text starts and ends. They are not part of the text.
A quote mark of the other kind, inside the text, is an ordinary character. The last line repeats one character.
It prints
It's late
Leo said "hi"
======
The outside quotes are not printed. A different quote mark inside the text is printed like any other character.
Fix the bug
This line stops with a SyntaxError. Fix it so that it prints the sentence, with the quote mark in It's.
The program prints the lines below. Your program must print exactly these lines.
Example run
It's time to go
Output
Python thinks the text ends at the second '. Which one is that?
Use the other kind of quotes on the outside.
print("It's time to go")
The single quote inside the text ended the string early. With double quotes outside, the single quote is an ordinary character.
Put the lines in order
Put the lines in order. The output starts with a line of dashes, then the title, then an empty line, then the first dish.
The program in the right order prints:
Target
----------
MENU
Soup
print("-"*10)
print("Soup")
print("MENU")
print()
Every print makes one line of output, in the order of the file.
print() with nothing inside makes the empty line, so it goes between the title and the dish.
print("-"*10)print("MENU")print()print("Soup")
Python runs the lines from top to bottom, and each print ends its line. print() alone prints an empty line.
Fill in the blank
Fill in the blank so that the program prints a line of twelve = characters.
print(*12)
The finished program prints:
Target
============
* with a number repeats a piece of text.
A piece of text needs quotes around it.
print("="*12)
"=" * 12 means the text = repeated 12 times. Without the quotes, = is not text.
Write code
Name tag. Print exactly three lines: a line of 15 - characters, then the text VISITOR, then another line of 15 - characters. Use repetition for the two lines of dashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
---------------
VISITOR
---------------
Output
Three lines of output need three print lines.
"-" * 15 gives the text - repeated 15 times.
print("-"*15)print("VISITOR")print("-"*15)
Each print starts a new line, and * with a number repeats a piece of text.
1.3 Printing numbers and calculations
print is not limited to text. You can give it numbers too — without quotes:
print(42)print(3.14)print(-7)
Output
42
3.14
-7
You can also give it a calculation. Python works out the answer first, and then prints the result:
print(10+5)print(100-37)print(6*7)print(20/4)
Output
15
63
42
5.0
Two things to notice:
* means multiply and / means divide. These are Python's operators for arithmetic; the full list is in → Chapter 4.
20 / 4 printed 5.0, not 5. In Python, / always gives a number with a decimal point, even when the division is exact. Whole numbers and decimal numbers are different types in Python → Chapter 2.
Text that looks like maths
Here is one of the most important ideas in this chapter. Compare:
print(10+5)print("10 + 5")
Output
15
10 + 5
Without quotes, 10 + 5 is a calculation, so Python works it out. With quotes, "10 + 5" is just text that happens to contain the characters 1, 0, space, +, space and 5. Python doesn't look inside text to see whether it resembles maths; it prints the characters exactly as they are.
The same goes for numbers. 42 is a number. "42" is text made of the two characters 4 and 2. They print the same, but Python treats them very differently — try adding them together and you'll get an error → Chapter 6.
Practice 1.3
Predict the output
What does it print?
print(8+4)print("8 + 4")print(8/4)
Quotes mean text, exactly as written. No quotes means Python works it out.
/ always gives a number with a decimal point.
It prints
12
8 + 4
2.0
The first line is a calculation and the second line is text. Division with / always gives a number with a decimal point.
Multiple choice
What does this line print?
print(30/6)
There are no quotes, so Python works out the result.
Look at what the chapter says about the result of /, even when the division is exact.
The answer is: 5.0
/ always gives a number with a decimal point, even when the division is exact.
Write code
Pizza slices. There are 3 pizzas, and each pizza is cut into 8 slices. 5 friends share all the slices equally. Print two lines: first the total number of slices, then the number of slices for each friend. Let Python do the calculations.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
24
4.8
Output
The total is the number of pizzas times the slices in one pizza.
For the second line, divide the total by the number of friends with /.
print(3*8)print(3*8/5)
A calculation without quotes is worked out first, and then print shows the result.
1.4 Printing several things at once
You can give print more than one argument by separating them with commas. Python prints them all on one line, with a single space between each:
This is the easiest way to mix text and numbers: put labels in quotes, calculations without quotes, and commas in between.
Look closely at the second line. We wrote "Total:" with no space after the colon, but the output has a space after it anyway. The space comes from the comma, not from the text. If you add your own space too, you'll get two:
print("Total: ",15)
Output
Total: 15
A small receipt
Let's put it together. This program prints a receipt for a small bookshop, working out the cost of each line:
Notice that 2 * 15 + 3 * 12 + 1 * 25 gives 91, which means Python did the multiplications before the additions — the same order of operations you learned in school maths → Chapter 4. Also notice that we had to repeat the prices to compute the total. That repetition is a sign we need variables, which let us store a value once and reuse it → Chapter 3.
Practice 1.4
Multiple choice
What does this line print?
print("Total:",9+6)
The first argument is text. The second argument is a calculation.
Where does the space between two arguments come from?
The answer is: Total: 15
Python works out 9 + 6, and print puts one space between its two arguments. The quotes are not printed.
Fill in the blank
One character is missing between the number and the last piece of text. Fill it in.
print("Width:",12"cm")
The finished program prints:
Target
Width: 12 cm
print gets three arguments here.
Which character separates one argument from the next?
print("Width:",12,"cm")
Arguments are separated with commas. print then shows them on one line with one space between them.
Fix the bug
Maya buys 3 packs of 4 pens. This line should print the label and then the number of pens, but it stops with a SyntaxError. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
Pens: 12
Output
The line gives print two things: a label and a calculation.
Two arguments need a comma between them.
print("Pens:",3*4)
Without the comma, Python cannot tell where the first argument ends. The comma separates the label from the calculation.
Put the lines in order
Put the lines of this receipt in order: the shop name, the kiwis, the plums, a line of dashes, and the total at the end.
The program in the right order prints:
Target
=== FRUIT SHOP ===
Kiwis : 8
Plums : 9
------------------
Total : 17
print("-"*18)
print("Kiwis :",4*2)
print("Plums :",3*3)
print("Total :",4*2+3*3)
print("=== FRUIT SHOP ===")
The output follows the order of the lines in the file.
The line of dashes comes just before the total.
print("=== FRUIT SHOP ===")print("Kiwis :",4*2)print("Plums :",3*3)print("-"*18)print("Total :",4*2+3*3)
Python runs the file from top to bottom, so the order of the print lines is the order of the receipt.
Write code
Cinema night. A cinema ticket costs 9 dollars and a box of popcorn costs 4 dollars. Leo buys 2 tickets and 3 boxes of popcorn. Print three lines, each with a label and a number that Python calculates: first the cost of the tickets, then the cost of the popcorn, then the total.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Tickets: 18
Popcorn: 12
Total: 30
Output
Each line is a label in quotes, a comma, and a calculation without quotes.
The total is the two costs added together: 2 * 9 + 3 * 4.
Labels go in quotes, calculations go without quotes, and commas go in between. Python multiplies before it adds.
1.5 Emojis and other languages
Python text isn't limited to English letters. Python 3 understands Unicode, an international standard that gives a number to every character in every writing system — including Chinese, Japanese, Arabic, Russian, Hindi, mathematical symbols and emojis.
print("Hello 👋")print("こんにちは · Привет · नमस्ते")print("Python is 🔥")print("Temperature: 25°C")print("π is roughly",22/7)
Output
Hello 👋
こんにちは · Привет · नमस्ते
Python is 🔥
Temperature: 25°C
π is roughly 3.142857142857143
On Windows, you can type an emoji in VS Code with the Windows key + . (full stop). On a Mac, use Control + ⌘ + Space.
Practice 1.5
Multiple choice
What does this line print?
print("Temperature:",20+5,"°C")
The symbol ° is an ordinary character inside the text.
There are three arguments. Count the commas, and remember what each comma adds to the output.
The answer is: Temperature: 25 °C
Text can hold any Unicode character. print puts one space between every two arguments, so there is a space before °C too.
1.6 Comments
A comment is a note for humans. Python ignores it completely. In Python, a comment starts with a # (called hash) and runs to the end of the line:
# This program greets the userprint("Good morning!")# a comment can also go after code# print("This line is switched off")
Output
Good morning!
Three uses appear in that example:
A whole-line comment explaining what the program does.
An end-of-line comment after some code. Put at least two spaces before the #, then one space after it.
Commenting out a line of code. Putting # in front of a line switches it off without deleting it. This is very handy while testing.
A # inside quotes is just a character in the text, not a comment:
print("Use # for comments")# only this part is a comment
Output
Use # for comments
Writing good comments
A comment should explain why the code does something, not repeat what it obviously does.
# Bad: says what the code already saysprint(60*60*24)# multiply 60 by 60 by 24# Good: says whyprint(60*60*24)# seconds in one day
Output
86400
86400
Anyone who can read Python can see the multiplication. What they can't see is why those numbers. A good comment adds information the code itself doesn't contain.
Comments over several lines
Python has no special "block comment" symbol. To write a longer note, start each line with #:
# Book Corner billing program# Prints an itemised receipt with a total.# Prices are in dollars.print("Receipt coming up...")
Output
Receipt coming up...
You may see text wrapped in three quotes, """like this""", used for notes at the top of files and functions. These are docstrings — a special kind of documentation that Python actually keeps and can show with help(). They're not ordinary comments, and they're covered with functions in → Chapter 19.
A comment starts at a # and runs to the end of the line.
A # inside quotes is a character of the text, not the start of a comment.
It prints
Red
Blue
Room #4
Python ignores the commented line and the comment after print("Blue"). The # inside the quotes is printed as text.
Fix the bug
The first line is meant to be a note for humans, but Python tries to run it. Fix the program so that it prints only the greeting. Keep the note.
The program prints the lines below. Your program must print exactly these lines.
Example run
Good evening!
Output
How do you tell Python to ignore a line?
Put a # at the start of the first line.
# This program greets the visitorprint("Good evening!")
A comment starts with #. Python ignores it completely, so only the print line runs.
1.7 How Python reads your file
Top to bottom, one line at a time
Python runs your file from the first line to the last, in order. Each line is usually one statement — one complete instruction. If you swap the order of the lines, you swap the order of the output:
print("first")print("second")print("third")
Output
first
second
third
print("third")print("first")print("second")
Output
third
first
second
This sounds obvious, but "Python does things in the order I wrote them" is the foundation for everything that follows. Later you'll learn how to change that order: skipping lines with if→ Chapter 11 and repeating lines with loops → Chapter 13.
Blank lines are ignored
Empty lines in your file don't do anything. Use them to separate your program into readable sections, the way paragraphs separate a story:
print("Welcome to the quiz")print("Question 1")print("Question 2")
Output
Welcome to the quiz
Question 1
Question 2
Notice the blank line in the file did not produce a blank line in the output. Only print() does that.
Indentation matters
In most of the code you'll write for now, every line should start at the very left edge, with no spaces in front. Python uses spaces at the start of a line — called indentation — to group lines together into blocks. A random indent where Python doesn't expect one is an error:
print("Hello")print("World")
Output
File "first.py", line 2
print("World")
IndentationError: unexpected indent
You will start using indentation on purpose in → Chapter 11. Until then, keep every line flush to the left.
Capital letters matter
Python is case-sensitive: print, Print and PRINT are three different names. Only the lowercase one exists:
Print("Hello")
Output
Traceback (most recent call last):
File "first.py", line 1, in <module>
Print("Hello")
^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?
Python even guessed what you meant. Text inside quotes, on the other hand, is printed exactly as written, capitals and all.
Spaces inside a line
Inside a line, Python is relaxed about spaces. All of these work:
print(10+5)print(10+5)print(10+5)
Output
15
15
15
They all work, but only the middle one is good style. Python's official style guide, called PEP 8, says: one space on each side of + and similar operators, and no spaces just inside the brackets. Also, don't put a space between print and its opening bracket. Following PEP 8 makes your code look like every other Python programmer's code, which makes it easier for everyone — including future you — to read.
Practice 1.7
Put the lines in order
Put the lines in order so that the steps are printed from step 1 to step 4.
The program in the right order prints:
Target
Step 1: fill the pot
Step 2: boil the water
Step 3: cook the pasta
Step 4: serve
print("Step 3: cook the pasta")
print("Step 2: boil the water")
print("Step 4: serve")
print("Step 1: fill the pot")
Python runs a file from the first line to the last.
The line that must be printed first goes at the top.
print("Step 1: fill the pot")print("Step 2: boil the water")print("Step 3: cook the pasta")print("Step 4: serve")
Python runs the lines in the order you wrote them. If you swap two lines, you swap two lines of output.
Multiple choice
Three of these lines run and print the same number. Which one stops with an error?
Inside a line, Python is relaxed about spaces.
Python is strict about capital letters in names.
The answer is: Print(10 + 5)
Python is case-sensitive, so Print is a different name and it is not defined. Extra spaces inside a line are bad style, but they are not an error.
Fix the bug
This program stops with an IndentationError before it prints anything. Fix it so that it prints three lines.
The program prints the lines below. Your program must print exactly these lines.
Example run
Ready
Steady
Go
Output
Spaces at the start of a line have a meaning in Python.
Every line must start at the left edge. Remove the spaces in front of the second line.
print("Ready")print("Steady")print("Go")
Python uses indentation to group lines, so a random indent is an error. For now, every line starts at the left edge.
1.8 Your first errors
You will see thousands of error messages as you learn to program. That is not a sign you are bad at it. It is simply how programming works: you write something, Python tells you what it couldn't understand, you fix it. Professionals see errors all day too.
The trick is to read the error message instead of panicking. Python's messages are very helpful once you know their layout.
Anatomy of an error message
Here's a program with a typo on line 2:
print("Start")prnt("Hello")print("End")
Output
Start
Traceback (most recent call last):
File "greet.py", line 2, in <module>
prnt("Hello")
^^^^
NameError: name 'prnt' is not defined. Did you mean: 'print'?
Read it from the bottom up:
Part
What it tells you
NameError
The type of error. A NameError means Python met a name it doesn't know.
name 'prnt' is not defined. Did you mean: 'print'?
The message: the details, often with a suggested fix.
^^^^
Points at the exact part of the line that caused the problem.
prnt("Hello")
A copy of the line that failed.
File "greet.py", line 2
Where it happened: which file and which line number.
Traceback (most recent call last):
The heading. A traceback traces back through the steps that led to the error. With longer programs it can list several steps; the last one is where it actually broke.
Notice also what happened to the output: Start was printed, then the program stopped. Line 3 never ran, so End was never printed. When Python hits an error while running, it stops at that line.
Two kinds of errors
Errors come in two big families, and the difference is worth understanding now.
Syntax errors happen when the code isn't valid Python at all — like a sentence with broken grammar. Python checks the whole file for these before running anything. So if there's a syntax error anywhere, not even the first line runs:
print("Line 1")print("Line 2")print("Line 3"
Output
File "lines.py", line 3
print("Line 3"
^
SyntaxError: '(' was never closed
Lines 1 and 2 are perfect, but nothing was printed. Python refused to start because line 3 is broken: the bracket opened on that line is never closed.
Runtime errors (Python calls them exceptions) happen while the program is running, when Python reaches a line it can't carry out. The NameError above was one: the grammar of prnt("Hello") is fine, but when Python got to it, there was no prnt. Everything before that line had already run.
Syntax error
Runtime error (exception)
When it's found
Before the program starts
While it runs, when Python reaches that line
Does anything run first?
No
Yes, every line before it
Message starts with
File "...", line N
Traceback (most recent call last):
Examples
SyntaxError, IndentationError
NameError, TypeError, ZeroDivisionError
You'll meet many more kinds of errors in → Chapter 10, and learn to handle them inside your programs in → Chapter 41.
The errors you'll see most this week
Forgetting the brackets (very common if you've seen old Python 2 tutorials):
print"Hello"
Output
File "first.py", line 1
print "Hello"
^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Forgetting a closing quote:
print("Hello)
Output
File "first.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal (detected at line 1)
Forgetting the quotes entirely:
print(Hello)
Output
Traceback (most recent call last):
File "first.py", line 1, in <module>
print(Hello)
^^^^^
NameError: name 'Hello' is not defined
Without quotes, Python thinks Hello is the name of something (like print is) and goes looking for it. There's nothing called Hello, so: NameError. Names are explained fully in → Chapter 3.
Dividing by zero:
print("Before")print(10/0)print("After")
Output
Before
Traceback (most recent call last):
File "first.py", line 2, in <module>
print(10 / 0)
~~~^~~
ZeroDivisionError: division by zero
Dividing by zero is impossible in maths, so Python stops with a ZeroDivisionError. Notice Before printed and After didn't — a runtime error, not a syntax error.
A method for fixing any error
Look at the last line: what type of error, and what does the message say?
Look at the line number and go to that line in your file.
Look where the ^ markers point.
If it's a syntax error and the line looks fine, check the line above too. A missing bracket or quote on one line is often only noticed on the next.
Fix one thing, run again, repeat.
Practice 1.8
Multiple choice
What happens when Python reaches line 2 of this program?
print("Before")print(8/0)print("Later")
The grammar of every line is fine, so the program starts and line 1 runs.
Which calculation is impossible in maths?
The answer is: It stops with a ZeroDivisionError
Dividing by zero is a runtime error. Before is printed, the program stops at line 2, and line 3 never runs.
Multiple choice
A file has five lines. Lines 1 to 4 are correct print lines. On line 5 the closing bracket is missing, which is a syntax error. How many lines of output appear when you run the file?
Is a missing bracket found before the program starts, or while it runs?
Python checks the whole file for syntax errors before it runs the first line.
The answer is: 0
Python checks the grammar of the whole file before it runs anything. With a syntax error anywhere, not even the first line runs.
Fix the bug
Python says '(' was never closed. Fix the line so that it prints the label and the result of the calculation.
The program prints the lines below. Your program must print exactly these lines.
Example run
Minutes in a day: 1440
Output
Count the opening brackets and the closing brackets.
The call to print needs a closing bracket at the end of the line.
print("Minutes in a day:",24*60)
Every opening bracket needs a closing bracket. The closing bracket marks the end of the call.
1.9 What happens when you run a program
You type python first.py, press Enter, and output appears. What happens in between? You don't need this to write programs, but it explains the behaviour you've just seen — especially why syntax errors stop everything before it starts.
Is Python compiled or interpreted?
You'll often hear "Python is an interpreted language". The truth is "both": Python first compiles your code to bytecode (steps 1–4), and then interprets that bytecode (step 5). Because the compiling is fast and happens automatically every time you run a file, it feels like Python runs your source code directly.
When you import one Python file into another → Chapter 42, Python saves the compiled bytecode in a folder called __pycache__, in files ending .pyc, so it can skip compiling next time. The file you run directly isn't cached this way. If you ever see a __pycache__ folder appear in your project, now you know what it is — and that it's safe to delete.
Practice 1.9
Multiple choice
Python runs a file in five steps. Which step finds syntax errors?
A syntax error means that the grammar of the code is broken.
Which step works out the structure of the program?
The answer is: Parsing the tokens into a tree
The parser builds a tree that describes the structure of the program. If the grammar is broken, Python stops at that step, before anything runs.
1.10 The shell shows things differently
Try this in the Python shell:
>>> "Hello"
'Hello'
>>> print("Hello")
Hello
Output
When the shell echoes a value, it shows strings with quotes around them. When you print a string, you get just the text. Why the difference?
The shell is a tool for programmers. It shows you the value in a way that makes its type obvious: the quotes tell you "this is text, not a number". print is for the people using your program, so it shows the text cleanly.
This helps you tell text and numbers apart in the shell:
>>> 42
42
>>> "42"
'42'
Output
The first is a number; the second is text that looks like a number. In a script, print would show both as 42. (The two ways of displaying a value are called str and repr; you'll create your own versions of them for your own types in → Chapter 48.)
Practice 1.10
Multiple choice
You type "Lima" in the Python shell (after >>>) and press Enter. What does the shell show?
The shell is a tool for programmers. It makes the type of a value easy to see.
The shell shows a string with quotes around it. Look at which kind of quotes the chapter's examples show.
The answer is: 'Lima'
The shell shows a string with single quotes around it, so you can see that the value is text. print shows only the text.
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
What is the difference between print("7 * 6") and print(7 * 6)?
Show the answer
print("7 * 6") prints the text 7 * 6 exactly as written, because it is in quotes. print(7 * 6) calculates the multiplication and prints 42.
Check yourself
In print("Hi"), which part is the function, which part is the argument, and what do the brackets do?
Show the answer
print is the function; "Hi" is the argument; the brackets call the function, passing it the argument.
Check yourself
Why does print('It's late') fail? Give two ways to fix it.
Show the answer
The ' in It's ends the string early, so Python sees 'It' followed by junk. Fix 1: use double quotes outside, print("It's late"). Fix 2: escape the inner quote with a backslash, print('It\'s late')→ Chapter 7.
Check yourself
What does print() with nothing inside the brackets do?
Show the answer
It prints an empty line.
Check yourself
What will print("a", "b", "c") show? Where do the spaces come from?
Show the answer
a b c. The spaces come from the commas: print puts one space between arguments.
Check yourself
A file has a perfectly fine print on line 1 and a SyntaxError on line 10. How many lines of output appear when you run it? What if line 10 has a NameError instead?
Show the answer
With a SyntaxError on line 10: zero lines, because Python checks the whole file before running anything. With a NameError on line 10: line 1's output appears (and anything else before line 10), then the program stops at line 10.
Check yourself
What's wrong with this comment, and how would you improve it?
print(365 * 24) # multiply 365 and 24
Show the answer
It repeats what the code obviously does. A better comment says why: # hours in a year.
Check yourself
Which line of an error message should you read first?
Show the answer
The last line: the error type and message.
Check yourself
In the shell, >>> "5" shows '5' but >>> 5 shows 5. What do the quotes tell you?
Show the answer
That the value is a string (text), not a number.
Check yourself
Put these steps of running a Python program in order: execute bytecode in the virtual machine, parse into a syntax tree, read the source code, compile to bytecode, split into tokens.
Show the answer
Read the source code → split into tokens → parse into a syntax tree → compile to bytecode → execute bytecode in the virtual machine.
The program prints the lines below. Your program must print exactly these lines.
Example run
Welcome to Python
Output
Python found the start of a piece of text. Where does that text end?
The quote at the start needs a matching quote before the closing bracket.
print("Welcome to Python")
The closing quote is missing (SyntaxError: unterminated string literal).
print("Welcome to Python")
Output
Welcome to Python
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
Good night
Output
Python is case-sensitive. Read the name of the function letter by letter.
The error message suggests the right name. Only the lowercase name exists.
print("Good night")
Python is case-sensitive; the function is print, lowercase (NameError).
print("Good night")
Output
Good night
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
My score is 95
Output
How do you call a function? Something is missing after the name print.
Put brackets around everything that print should show.
print("My score is",95)
print needs brackets in Python 3 (SyntaxError: Missing parentheses).
print("My score is",95)
Output
My score is 95
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
Start
Middle
End
Output
Look at the start of every line. Which line does not begin at the left edge?
Remove the spaces in front of the second line.
print("Start")print("Middle")print("End")
Line 2 has stray spaces at the start (IndentationError: unexpected indent).
print("Start")print("Middle")print("End")
Output
Start
Middle
End
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
Your name is Alex
Output
Without quotes, Python tries to read the words as code.
The words are text, so put one pair of quotes around all of them.
print("Your name is Alex")
The text has no quotes, so Python tries to read Your name is Alex as code and fails with a SyntaxError. Put it in quotes.
print("Your name is Alex")
Output
Your name is Alex
Coding problems
Write code · Easy
About you. Print your name, your city and your favourite subject, each on its own line.
This one is not checked automatically. Run your program, then compare it with the book's answer.
Output
Show the book's answer
print("Alex")print("Tokyo")print("Data Science")
Output
Alex
Tokyo
Data Science
Write code · Easy
Framed title. Print the word PYTHON with a line of 20 * characters above and below it. Use * repetition, not 20 typed stars.
Print exactly three lines: 20 * characters, then PYTHON, then 20 * characters again.
The program prints the lines below. Your program must print exactly these lines.
Example run
********************
PYTHON
********************
Output
Section 1.2 showed how to repeat a piece of text with * and a number.
The first and the last line are the same: the text "*" repeated 20 times.
print("*"*20)print("PYTHON")print("*"*20)
print("*"*20)print("PYTHON")print("*"*20)
Output
********************
PYTHON
********************
Write code · Easy
Quick maths. Print the number of seconds in an hour, in a day, and in a 365-day year, each with a label, like Seconds in an hour: 3600.
Print the seconds in an hour first, then in a day, then in a year. Let Python do the multiplication.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Seconds in an hour: 3600
Seconds in a day: 86400
Seconds in a year: 31536000
Output
One hour has 60 minutes of 60 seconds each. One day has 24 hours.
Write each line as a label in quotes, then a comma, then a calculation such as 60 * 60.
print("Seconds in an hour:",60*60)print("Seconds in a day:",60*60*24)print("Seconds in a year:",60*60*24*365)
print("Seconds in an hour:",60*60)print("Seconds in a day:",60*60*24)print("Seconds in a year:",60*60*24*365)
Output
Seconds in an hour: 3600
Seconds in a day: 86400
Seconds in a year: 31536000
Write code · Medium
Mark sheet. A student scored 88, 92, 79, 95 and 84. Print each subject with its mark, then a line with the total, and a line with the average (total divided by 5). Let Python do all the arithmetic.
Print the five marks in the order given, then the total, then the average. You can choose the subject names.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Maths : 88
Physics : 92
Chemistry: 79
English : 95
Computer : 84
Total : 438
Average : 87.6
Output
For the total, write all five marks with + between them, without quotes.
For the average, put the whole sum in brackets and divide by 5: (...) / 5. Without the brackets only the last mark is divided.
Shopping bill. A shop sells pens at $2, notebooks at $5 and a calculator at $15. A customer buys 4 pens, 3 notebooks and 1 calculator. Print an itemised bill showing each line's cost, a subtotal, 8% sales tax on the subtotal, and the grand total. Every number must be calculated by Python, not by you.
Print the cost of the pens first, then the notebooks, then the calculator, then the subtotal, the tax and the grand total.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
The tax is 8% of the subtotal, which is the subtotal × 8 / 100.
print("========== BILL ==========")print("Pens 4 x 2 :",4*2)print("Notebooks 3 x 5 :",3*5)print("Calculator 1 x 15 :",1*15)print("--------------------------")print("Subtotal :",4*2+3*5+1*15)print("Sales tax 8% :",(4*2+3*5+1*15)*8/100)print("Grand total :",(4*2+3*5+1*15)*108/100)print("==========================")
Output
========== BILL ==========
Pens 4 x 2 : 8
Notebooks 3 x 5 : 15
Calculator 1 x 15 : 15
--------------------------
Subtotal : 38
Sales tax 8% : 3.04
Grand total : 41.04
==========================
The grand total multiplies by 108/100 because subtotal + 8% of subtotal = 108% of subtotal. Writing the subtotal calculation three times is clumsy; variables fix that in → Chapter 3.
Write code · Hard
Times table, the hard way. Print the 7 times table from 7 × 1 to 7 × 10, in the format 7 x 1 = 7. You may only use print and arithmetic. Then write down: what part of the program felt repetitive? (You'll fix that repetition with a loop in → Chapter 14.)
Print ten lines in exactly this form: 7 x 1 = 7. Use the letter x in the label, and let Python calculate the result.
The program prints the lines below. Your program must print exactly these lines.
Example run
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Output
Each line has a label in quotes, a comma, and a calculation: print("7 x 1 =", 7 * 1).
The comma puts the space before the result, so the label ends with = and no space.
print("7 x 1 =",7*1)print("7 x 2 =",7*2)print("7 x 3 =",7*3)print("7 x 4 =",7*4)print("7 x 5 =",7*5)print("7 x 6 =",7*6)print("7 x 7 =",7*7)print("7 x 8 =",7*8)print("7 x 9 =",7*9)print("7 x 10 =",7*10)
print("7 x 1 =",7*1)print("7 x 2 =",7*2)print("7 x 3 =",7*3)print("7 x 4 =",7*4)print("7 x 5 =",7*5)print("7 x 6 =",7*6)print("7 x 7 =",7*7)print("7 x 8 =",7*8)print("7 x 9 =",7*9)print("7 x 10 =",7*10)
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
The repetitive part: ten nearly identical lines where only one number changes. A for loop will reduce this to two lines.
Write code · Hard
Error collector. Write five separate tiny programs that each produce a different error type: SyntaxError, IndentationError, NameError, ZeroDivisionError, and one more of your choice. For each, write a comment explaining in your own words why it happens.
This one is not checked automatically. Run your program, then compare it with the book's answer.
Output
Show the book's answer
One possible set (each is a separate program):
# SyntaxError: the bracket is never closed, so this isn't valid Pythonprint("oops"
Output
File "e9a.py", line 2
print("oops"
^
SyntaxError: '(' was never closed
# IndentationError: a line starts with spaces where Python doesn't expect anyprint("one")print("two")
Output
File "e9b.py", line 3
print("two")
IndentationError: unexpected indent
# NameError: Python doesn't know any name called 'pront'pront("hello")
Output
Traceback (most recent call last):
File "e9c.py", line 2, in <module>
pront("hello")
^^^^^
NameError: name 'pront' is not defined. Did you mean: 'print'?
# ZeroDivisionError: dividing by zero has no answerprint(1/0)
Output
Traceback (most recent call last):
File "e9d.py", line 2, in <module>
print(1 / 0)
~~^~~
ZeroDivisionError: division by zero
# TypeError: you can't add text and a number togetherprint("Age: "+20)
Output
Traceback (most recent call last):
File "e9e.py", line 2, in <module>
print("Age: " + 20)
~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
The last one is a TypeError: you'll learn exactly why it happens, and two ways to fix it, in → Chapter 6.
Chapter project: Class trip notice
Project
Print a notice for a class trip. A class of 24 students visits a science museum. A ticket costs 6 dollars for each student, and the bus costs 90 dollars for the whole class.
Write a program that prints this notice, in this order:
a line of 24 = characters (use repetition)
the title SCIENCE MUSEUM TRIP
the same line of 24 = characters again
an empty line
Students: and the number of students
Tickets: and the cost of all the tickets
Bus: and the cost of the bus
Total: and the cost of the tickets plus the bus
Each student pays: and the total divided by the number of students
an empty line
the closing message See you on Friday!
Python must do every calculation. On lines 5 to 9, use a comma between the label and the number, so there is exactly one space after the colon.
Also write a comment on the first line of your file that says what the program does.
The program prints the lines below. Your program must print exactly these lines.
Example run
========================
SCIENCE MUSEUM TRIP
========================
Students: 24
Tickets: 144
Bus: 90
Total: 234
Each student pays: 9.75
See you on Friday!
Output
Build the notice one line at a time and run the program after each new line. print() with nothing inside gives an empty line.
The cost of the tickets is the number of students times the price of one ticket. The total is that cost plus the bus.
For the last number, put the whole total in brackets and then divide: (24 * 6 + 90) / 24. Without the brackets, only the bus cost is divided.
# Prints the notice and the costs for the class trip to the museumprint("="*24)print("SCIENCE MUSEUM TRIP")print("="*24)print()print("Students:",24)print("Tickets:",24*6)print("Bus:",90)print("Total:",24*6+90)print("Each student pays:",(24*6+90)/24)print()print("See you on Friday!")
The program uses repetition for the frame, print() for empty lines, commas to put labels next to calculations, and a comment for the reader. The last number has a decimal point because / always gives one.