Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 1

Your First Program

This lesson goes with Episode 1 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

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?

Choose one answer

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!

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:

print("Line one")
print("Line two")
print("Line three")

Output

Line one
Line two
Line three

Blank lines

Calling print with nothing inside the brackets prints an empty line. It is useful for spacing out your output:

print("Chapter 1")
print()
print("Your First Program")

Output

Chapter 1

Your First Program

The brackets are still required. print() means "call print with no arguments"; plain print without brackets does nothing at all in a script.

Repeating text

As a small preview, you can repeat a piece of text with *:

print("=" * 30)
print("REPORT CARD")
print("=" * 30)

Output

==============================
REPORT CARD
==============================

"=" * 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)

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

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
  1. print("-" * 10)
  2. print("Soup")
  3. print("MENU")
  4. print()

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

============

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
---------------

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)

Multiple choice

What does this line print?

print(30 / 6)
Choose one answer

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

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:

print("Python", "is", "fun")
print("Total:", 10 + 5)
print("Marks:", 92, "out of", 100)

Output

Python is fun
Total: 15
Marks: 92 out of 100

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:

print("===== BOOK CORNER =====")
print("Notebook     x2 :", 2 * 15)
print("Pen pack     x3 :", 3 * 12)
print("Backpack     x1 :", 1 * 25)
print("----------------------")
print("Total           :", 2 * 15 + 3 * 12 + 1 * 25)
print("Thank you, visit again!")

Output

===== BOOK CORNER =====
Notebook     x2 : 30
Pen pack     x3 : 36
Backpack     x1 : 25
----------------------
Total           : 91
Thank you, visit again!

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)
Choose one answer

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

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

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
  1. print("-" * 18)
  2. print("Kiwis :", 4 * 2)
  3. print("Plums :", 3 * 3)
  4. print("Total :", 4 * 2 + 3 * 3)
  5. print("=== FRUIT SHOP ===")

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

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")
Choose one answer

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 user
print("Good morning!")  # a comment can also go after code
# print("This line is switched off")

Output

Good morning!

Three uses appear in that example:

  1. A whole-line comment explaining what the program does.
  2. An end-of-line comment after some code. Put at least two spaces before the #, then one space after it.
  3. 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 says
print(60 * 60 * 24)  # multiply 60 by 60 by 24

# Good: says why
print(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.

Practice 1.6

Predict the output

What does it print?

print("Red")
# print("Green")
print("Blue")  # print("Pink")
print("Room #4")

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!

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
  1. print("Step 3: cook the pasta")
  2. print("Step 2: boil the water")
  3. print("Step 4: serve")
  4. print("Step 1: fill the pot")

Multiple choice

Three of these lines run and print the same number. Which one stops with an error?

Choose one answer

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

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

  1. Look at the last line: what type of error, and what does the message say?
  2. Look at the line number and go to that line in your file.
  3. Look where the ^ markers point.
  4. 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.
  5. 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")
Choose one answer

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?

Choose one answer

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

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?

Choose one answer

1.10 The shell shows things differently

Try this in the Python shell:

>>> "Hello"
'Hello'
>>> print("Hello")
Hello

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'

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?

Choose one answer

+ 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.

Predict the output

Predict the output

print("2 + 2")
print(2 + 2)
print("2", "+", "2", "=", 2 + 2)

Predict the output

print("A")
# print("B")
print("C")  # print("D")

Predict the output

print("Total:", 5 * 4 + 2)
print()
print("-" * 5, "END", "-" * 5)

Fix the bug

Fix the bug

The program prints the lines below. Your program must print exactly these lines.

Example run

Welcome to Python

Fix the bug

The program prints the lines below. Your program must print exactly these lines.

Example run

Good night

Fix the bug

The program prints the lines below. Your program must print exactly these lines.

Example run

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

Fix the bug

The program prints the lines below. Your program must print exactly these lines.

Example run

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.

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
********************

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

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

Write code · Medium

Emoji weather report. Print a three-day weather report using emojis, with each day on its own line and a blank line before a closing message.

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer
print("Weather report")
print("Monday    ☀️  32°C")
print("Tuesday   ⛅  29°C")
print("Wednesday 🌧️  24°C")
print()
print("Carry an umbrella on Wednesday! ☂️")

Output

Weather report
Monday    ☀️  32°C
Tuesday   ⛅  29°C
Wednesday 🌧️  24°C

Carry an umbrella on Wednesday! ☂️

Write code · Medium

Rocket. Use several print lines to draw this rocket exactly:

The spaces at the start of each line are part of the drawing. Count them carefully.

The program prints the lines below. Your program must print exactly these lines.

Example run

   /\
  /  \
  |  |
  |  |
 /____\
  /\/\

Write code · Hard

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.

Example run

Pens       : 8
Notebooks  : 15
Calculator : 15
Subtotal   : 38
Sales tax  : 3.04
Grand total: 41.04

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

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.

Show the book's answer

One possible set (each is a separate program):

# SyntaxError: the bracket is never closed, so this isn't valid Python
print("oops"

Output

  File "e9a.py", line 2
    print("oops"
         ^
SyntaxError: '(' was never closed
# IndentationError: a line starts with spaces where Python doesn't expect any
print("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 answer
print(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 together
print("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:

  1. a line of 24 = characters (use repetition)
  2. the title SCIENCE MUSEUM TRIP
  3. the same line of 24 = characters again
  4. an empty line
  5. Students: and the number of students
  6. Tickets: and the cost of all the tickets
  7. Bus: and the cost of the bus
  8. Total: and the cost of the tickets plus the bus
  9. Each student pays: and the total divided by the number of students
  10. an empty line
  11. 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!