Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 3

Variables and Names

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

0 of 0 done

In Chapter 1, our bookshop receipt typed the price of every item twice: once for its line and once again in the total. If the price of a notebook went up, you'd have to find and change every copy. Programs need a way to store a value once and refer to it by name. That's what variables do, and they're the subject of this chapter.

3.1 Giving a value a name

Here is the receipt again, rewritten with variables:

notebook = 15
pen_pack = 12
backpack = 25

print("Notebook     x2 :", 2 * notebook)
print("Pen pack     x3 :", 3 * pen_pack)
print("Backpack     x1 :", 1 * backpack)
print("Total           :", 2 * notebook + 3 * pen_pack + 1 * backpack)

Output

Notebook     x2 : 30
Pen pack     x3 : 36
Backpack     x1 : 25
Total           : 91

The first three lines are assignment statements. notebook = 15 means: "from now on, the name notebook refers to the value 15." After that, anywhere you write notebook, Python uses 15.

A variable is a name that refers to a value. Now, if a notebook goes up to $20, you change one line, and every line that uses notebook is correct automatically. The program also reads better: 2 * notebook says what it means, while 2 * 15 leaves you guessing what 15 is.

Practice 3.1

Predict the output

What does it print?

ticket = 12
print("Two tickets:", 2 * ticket)
print("Five tickets:", 5 * ticket)

Fill in the blank

Fill in the blank with the name of the variable, so that a change of the price on the first line also changes the result.

notebook = 20
print("Three notebooks:", 3 * )

The finished program prints:

Target

Three notebooks: 60

3.2 How assignment works

An assignment has three parts:

 price  =   15
  │     │    │
  │     │    └─ an expression: the value to store (worked out first)
  │     └─ the assignment operator
  └─ the name

Python carries it out in two steps:

  1. Work out the right-hand side to get a value.
  2. Attach the name on the left to that value.

The right side can be any expression, including a calculation or other variables:

price = 40
quantity = 3
total = price * quantity
print(total)

Output

120

For the third line, Python first works out price * quantity, which is 40 * 3, which is 120. Only then does it attach the name total to 120.

= does not mean "equals"

In maths, x = 5 states a fact: x and 5 are equal, now and forever. In Python, = is an action: make this name refer to this value. It's better read aloud as "gets" or "is set to": "total gets price times quantity".

The difference matters. In maths, x = x + 1 is nonsense — no number equals itself plus one. In Python, it's perfectly sensible:

age = 21
age = age + 1
print(age)

Output

22

Step 1: work out the right side, age + 1, using the current value of age: 21 + 1 is 22. Step 2: attach the name age to 22. The old value is replaced.

Because the name always goes on the left, writing the assignment backwards is an error:

5 = x

Output

  File "variables.py", line 1
    5 = x
    ^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

You can't make 5 refer to something else; 5 is a literal, not a name. Python suggests ==, which is the operator that really does mean "is equal to?" → Chapter 5.

Practice 3.2

Put the lines in order

Put the lines in order. The program works out a total, adds a delivery cost to it, and prints it.

The program in the right order prints:

Target

Total with delivery: 27
  1. total = price * 4
  2. total = total + 3
  3. print("Total with delivery:", total)
  4. price = 6

Write code

Pizza party. Store 3 in a variable named pizzas and 8 in a variable named slices_each. Work out the total number of slices from these two variables and store it in a third variable named total_slices. Then print total_slices.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Total slices: 24

3.3 Using variables

Once a name refers to a value, you can use the name anywhere you could use the value: in print, in calculations, inside type():

city = "Tokyo"
temperature = 31.5
print(city, temperature)
print(type(city), type(temperature))
print(temperature * 9 / 5 + 32)

Output

Tokyo 31.5
<class 'str'> <class 'float'>
88.7

Notice print(city) shows Tokyo, not the word city. Without quotes, city is a name, and Python looks up its value. With quotes, "city" would be four letters of text. This is the same rule you learned in Chapter 1: quotes = text, exactly as written; no quotes = Python works it out. Working out a name means looking up its value.

In the shell, typing a variable's name shows its value:

>>> marks = 87
>>> marks
87
>>> marks + 10
97
>>> marks
87

marks + 10 calculated 97 and showed it, but didn't change marks. Only an assignment changes what a name refers to.

A name must be assigned before it's used

Python runs your file from top to bottom. If you use a name before the line that assigns it, Python has never heard of it:

print(total)
total = 500

Output

Traceback (most recent call last):
  File "variables.py", line 1, in <module>
    print(total)
          ^^^^^
NameError: name 'total' is not defined

Line 2 would have created total, but Python never got there. The same error appears if you mistype a name. Remember that capitals matter:

score = 10
print(Score)

Output

Traceback (most recent call last):
  File "variables.py", line 2, in <module>
    print(Score)
          ^^^^^
NameError: name 'Score' is not defined. Did you mean: 'score'?

Defining a name means assigning it (score = 10). Referencing it means using it (print(score)). A name must be defined before it's referenced.

Practice 3.3

Multiple choice

What does this program show?

city = "Lima"
print("city")
Choose one answer

Fix the bug

This program stops with a NameError. Fix it so that it prints the final score.

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

Example run

Final score: 45

Multiple choice

What happens when this program runs?

width = 4
print(width * height)
height = 3
Choose one answer

3.4 Changing a variable

A variable can be given a new value at any time. That's why it's called a variable: its value can vary.

lives = 3
print("Lives:", lives)
lives = 2
print("Lives:", lives)
lives = lives - 1
print("Lives:", lives)

Output

Lives: 3
Lives: 2
Lives: 1

Tracing a program

When variables change, it helps to trace the program: go line by line and write down every variable's value after each line. Here's a short program and its trace table:

a = 5
b = a
a = 10
b = b + a
print(a, b)

Output

10 15
After line a b What happened
1 a = 5 5 — a is created
2 b = a 5 5 b gets the value a has right now
3 a = 10 10 5 a changes; b does not
4 b = b + a 10 15 5 + 10

Line 3 is the interesting one. After b = a, you might expect b to follow a around, so that changing a also changes b. It doesn't. b = a means "make b refer to whatever a refers to at this moment". To see exactly why, we need a better picture of what a variable is.

Practice 3.4

Predict the output

Trace this program on paper, then type what it prints.

x = 2
y = x
x = 7
y = y + x
print(x, y)

Put the lines in order

Put the lines in order. The program shows a level, goes up one level, and shows the new level.

The program in the right order prints:

Target

Start level: 1
Next level: 2
  1. level = 1
  2. level = level + 1
  3. print("Start level:", level)
  4. print("Next level:", level)

3.5 Variables are labels, not boxes

Many books describe a variable as a box with a name written on it, and the value stored inside. For Python, that picture is wrong, and it will mislead you later. A better picture is a label (or a name tag) tied to a value with a string.

Remember from Chapter 2 that every value is an object sitting somewhere in memory. An assignment doesn't copy the object into a box. It ties a name tag to the object.

a = 5            a ──────► 5

b = a            a ──────► 5
                 b ──────┘          (two tags, one object)

a = 10           a ──────► 10
                 b ──────► 5        (a's tag moved; b's didn't)

b = a ties a second tag to the same object that a is tied to. Then a = 10 creates a new object, 10, and moves the a tag onto it. The b tag is still tied to 5. Nothing ever happened to b.

Programmers say a variable refers to (or points to, or is bound to) an object. The name and the object are separate things: the name lives in your program's list of names, and the object lives in memory.

Seeing identity with id()

Every object has an identity, a number that's unique to it while it exists. In CPython it's the object's memory address. The built-in id() shows it:

a = 1000
b = a
print(id(a))
print(id(b))
print(id(a) == id(b))

Output

...
...
True

The actual numbers are different every time you run the program (they're memory addresses), but the two are always equal: a and b are two names for one object. There's also an operator, is, that asks exactly this question — "are these the same object?" → Chapter 5.

With numbers and text, it never matters that two names share an object, because numbers and strings can't be changed in place; you can only make a name refer to a different value. With lists, which can be changed in place, sharing becomes very important, and the label picture is what will save you → Chapter 26.

Practice 3.5

Predict the output

id() gives the identity of an object. This program compares two identities two times. What does it print?

This uses the operator ==, which is taught in Chapter 5.

x = 1000
y = x
print(id(x) == id(y))
x = 2000
print(id(x) == id(y))

3.6 Dynamic typing

In Chapter 2 you saw that the type belongs to the value, not to the code. Variables are just labels, so a label has no type of its own. The same name can refer to an int now and a str later:

data = 42
print(data, type(data))
data = "forty-two"
print(data, type(data))
data = 42.0
print(data, type(data))

Output

42 <class 'int'>
forty-two <class 'str'>
42.0 <class 'float'>

This is called dynamic typing: types are checked while the program runs, by looking at the values. Languages like Java and C use static typing: you declare each variable's type in advance (int data = 42;), and the variable can only ever hold that type.

Dynamic typing makes Python quick to write and easy to start with. The cost is that a mistake like putting text where a number was expected is only discovered when that line runs. Professionals often add optional type hints to their code so tools can catch such mistakes early → Chapter 54.

Practice 3.6

Multiple choice

What does this program print?

data = 3
data = "three"
data = 3.5
print(type(data))
Choose one answer

3.7 Rules for names

A name (programmers also say identifier) must follow these rules:

  1. It can contain letters, digits and underscores (_).
  2. It can't start with a digit.
  3. It can't contain spaces or symbols like -, @, $, . or !.
  4. It can't be a keyword (see below).
  5. Capitals matter: score, Score and SCORE are three different names.
Name Valid? Why
total ✓
total_marks ✓ underscores are allowed
marks2025 ✓ digits are fine after the first character
_count ✓ can start with an underscore
2nd_place ✗ starts with a digit
first name ✗ contains a space
my-score ✗ - is the minus sign
price$ ✗ $ is not allowed
class ✗ keyword

Each broken rule gives a slightly different error. A name starting with a digit:

2nd_place = "Maya"

Output

  File "variables.py", line 1
    2nd_place = "Maya"
    ^
SyntaxError: invalid decimal literal

Python saw 2 and started reading a number. Then it hit n, which can't be part of a number.

A name with a hyphen:

my-score = 50

Output

  File "variables.py", line 1
    my-score = 50
    ^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Python read my-score as "my minus score" — a calculation, not a name — and you can't assign to a calculation.

A name with a space:

first name = "Alex"

Output

  File "variables.py", line 1
    first name = "Alex"
          ^^^^
SyntaxError: invalid syntax

Keywords

Keywords are words with a special meaning in Python's grammar, like if, for and True. You can't use them as names. Python 3.15 has 35 of them:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

Don't try to memorise this list. VS Code colours keywords differently, and you'll learn each one as the book reaches it. Using one as a name is a syntax error:

class = "10th B"

Output

  File "variables.py", line 1
    class = "10th B"
          ^
SyntaxError: invalid syntax

Python also has five soft keywords: match, case, type, _ and lazy. They act as keywords only in certain places (for example match and case in pattern matching → Chapter 12, and lazy in lazy imports, new in Python 3.15 → Chapter 42), and are ordinary names everywhere else. So match = 5 works, but it's confusing, so avoid it.

You can ask Python for the list itself:

import keyword
print(len(keyword.kwlist))
print(keyword.softkwlist)
print(keyword.iskeyword("for"))

Output

35
['_', 'case', 'lazy', 'match', 'type']
True

This uses import, which is taught in Chapter 17.

This site runs Python undefined. Its result for this example is a little different from the book (Python undefined).
35
['_', 'case', 'match', 'type']
True

Names in other languages

Names can contain letters from any language, because Python 3 understands Unicode:

año = 2026
名前 = "Alex"
print(名前, año)

Output

Alex 2026

This works, but almost all Python code in the world uses English names, and other people may not be able to type yours. Keep names in English letters; put any language you like inside the strings.

Practice 3.7

Multiple choice

Only one of these is a valid name. Which one?

Choose one answer

Fix the bug

Both names in this program break a rule for names, so Python refuses to run it. Give the two variables valid names so that the program prints the prize money.

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

Example run

Prize money: 150

3.8 Naming conventions

The rules say what Python allows. Conventions are the habits that Python programmers agree on, mostly written down in PEP 8. Following them makes your code instantly readable to other Python programmers.

Kind of name Convention Example
Variables and functions snake_case: lowercase words joined by underscores total_marks, student_name
Constants UPPER_SNAKE_CASE TAX_RATE, MAX_PLAYERS
Classes CapWords (also called PascalCase) → Chapter 44 BankAccount
"Internal use" names one leading underscore → Chapter 45 _cache
Special Python names two underscores on each side ("dunder") __name__

A few more guidelines:

  • Choose meaningful names. marks beats m; seconds_per_day beats x. Single letters are fine only for very short, obvious uses, like x and y for coordinates.
  • Don't be too long either. the_total_marks_of_the_student_in_all_subjects is tiring; total_marks says the same.
  • Avoid l (lowercase L), O (capital o) and I (capital i) as single-letter names. In many fonts they look like 1 and 0.
  • Don't use names that start and end with two underscores for your own variables. Those are reserved for Python's special names. For example, every program has a name __name__ already set up for it:
print(__name__)

Output

__main__

"__main__" means "this file is the one being run directly". You'll find out why that's useful in → Chapter 42.

Practice 3.8

Multiple choice

You need a variable for the total marks of a student. Which name follows the Python convention for variables?

Choose one answer

3.9 Don't reuse built-in names

print, type, id, input, sum, max, min, list and str are built-in names. They're not keywords, so Python lets you assign to them. But if you do, you hide (programmers say shadow) the built-in, and it stops working:

print = "Welcome!"
print("Hello")

Output

Traceback (most recent call last):
  File "variables.py", line 2, in <module>
    print("Hello")
    ~~~~~^^^^^^^^^
TypeError: 'str' object is not callable

After line 1, the name print refers to a string. Line 2 tries to call that string as if it were a function, and strings can't be called. The error message makes sense once you know what happened, but it's baffling if you don't, especially when the assignment was 200 lines earlier.

This one catches lots of beginners:

type = "admin"
print(type(5))

Output

Traceback (most recent call last):
  File "variables.py", line 2, in <module>
    print(type(5))
          ~~~~^^^
TypeError: 'str' object is not callable

The fix is to choose a different name (user_type, account_type). If it happens in the shell, del (section 3.12) removes your name and uncovers the built-in again:

print = "oops"
del print
print("print works again")

Output

print works again

Practice 3.9

Fix the bug

The second line works, but the third line stops with 'str' object is not callable. Fix the program so that both lines print.

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

Example run

Kind of user: student
<class 'float'>

3.10 Several assignments at once

Multiple assignment

You can assign several names in one line by separating both sides with commas:

name, city, age = "Alex", "Tokyo", 21
print(name)
print(city)
print(age)

Output

Alex
Tokyo
21

The first name gets the first value, the second gets the second, and so on. This is called multiple assignment or unpacking. The numbers on each side must match:

a, b = 1, 2, 3

Output

Traceback (most recent call last):
  File "variables.py", line 1, in <module>
    a, b = 1, 2, 3
    ^^^^
ValueError: too many values to unpack (expected 2, got 3)
a, b, c = 1, 2

Output

Traceback (most recent call last):
  File "variables.py", line 1, in <module>
    a, b, c = 1, 2
    ^^^^^^^
ValueError: not enough values to unpack (expected 3, got 2)

One value, several names

To give several names the same value, chain the = signs:

wins = losses = draws = 0
print(wins, losses, draws)

Output

0 0 0

All three names are tied to the same object, 0. With numbers that's harmless; when you get to lists, be careful with this form → Chapter 26.

Swapping two values

A classic problem: you have a = 1 and b = 2, and you want to swap them. A first attempt fails:

a = 1
b = 2
a = b
b = a
print(a, b)

Output

2 2

After a = b, both names refer to 2, and the 1 is lost. In most languages, you need a third, temporary variable:

a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)

Output

2 1

In Python, multiple assignment does it in one line:

a = 1
b = 2
a, b = b, a
print(a, b)

Output

2 1

This works because Python finishes the whole right side first. It reads b, a to get the values 2, 1, and only then attaches the names: a to 2, and b to 1. (Behind the scenes, the right side becomes a tuple → Chapter 30.)

Practice 3.10

Fill in the blank

Fill in the blank so that the two values are swapped in one line. Use the two names, not the two pieces of text.

left = "fork"
right = "knife"
left, right = 
print(left, right)

The finished program prints:

Target

knife fork

Predict the output

What does it print?

x, y, z = 5, 10, 15
x, y = y, z
print(x, y, z)

Put the lines in order

Put the lines in order. The program swaps two values with the help of a third, temporary variable.

The program in the right order prints:

Target

blue red
  1. left, right = "red", "blue"
  2. right = temp
  3. temp = left
  4. print(left, right)
  5. left = right

Write code

Swap the cups. The program prints the two drinks two times. Add one line between the two print lines that swaps the values of left and right, so that the second line shows the drinks the other way round. Use the names, and do not type the drinks again.

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

Example run

tea milk
milk tea

3.11 Updating a variable: += and friends

Changing a variable based on its own value is so common that Python has a shorthand. score += 10 means exactly score = score + 10:

score = 0
score += 10     # score = score + 10
score += 5      # score = score + 5
score -= 3      # score = score - 3
print(score)

Output

12

These are called augmented assignment operators. There's one for each arithmetic operator:

Shorthand Means
x += 3 x = x + 3
x -= 3 x = x - 3
x *= 3 x = x * 3
x /= 3 x = x / 3
x //= 3 x = x // 3
x %= 3 x = x % 3
x **= 3 x = x ** 3

//, % and ** are covered in → Chapter 4. Like the long form, augmented assignment needs the variable to exist already:

count += 1

Output

Traceback (most recent call last):
  File "variables.py", line 1, in <module>
    count += 1
    ^^^^^
NameError: name 'count' is not defined. Did you mean: 'round'?

Python can't add 1 to a count that was never started. (It guessed you meant round, a built-in with a similar spelling. Its guesses aren't always right!) Start the count first: count = 0.

Practice 3.11

Fill in the blank

Fill in the blank with one augmented assignment operator, so that 5 coins are added to the count.

coins = 10
coins  5
print(coins)

The finished program prints:

Target

15

Predict the output

What does it print?

stock = 20
stock -= 5
stock *= 2
stock += 1
print(stock)

Fix the bug

Two visitors enter a shop, and the program should count them and print Visitors: 2. Now it stops with a NameError. Fix it.

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

Example run

Visitors: 2

Write code

Step counter. Start a variable named steps at 0. Add 1200 to it with += and print it. Add 800 more with += and print it. Then double it with *= and print it. The program prints three lines.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Morning: 1200
Evening: 2000
Doubled: 4000

3.12 Deleting a name: del

The del statement removes a name:

temperature = 31
print(temperature)
del temperature
print(temperature)

Output

31
Traceback (most recent call last):
  File "variables.py", line 4, in <module>
    print(temperature)
          ^^^^^^^^^^^
NameError: name 'temperature' is not defined

After del, the name is gone, exactly as if it had never been assigned. You can delete several at once with del a, b, c.

del removes the name tag, not necessarily the object. If no other name refers to the object, Python frees its memory automatically → Chapter 59. In everyday programs you rarely need del for variables, because Python cleans up for you. You'll use it more with lists and dictionaries → Chapter 27.

Practice 3.12

Predict the output

What does it print?

first = 30
second = first
del first
second += 5
print(second)

3.13 Constants

A constant is a value that's not meant to change while the program runs, like a sales tax rate or the number of days in a week. Python has no way to lock a variable. Instead, programmers write the name in capitals as a signal to each other: don't change this.

TAX_RATE = 8
subtotal = 250
tax = subtotal * TAX_RATE / 100
print("Subtotal:", subtotal)
print("Tax:", tax)
print("Total:", subtotal + tax)

Output

Subtotal: 250
Tax: 20.0
Total: 270.0

Putting constants at the top of a file, with clear names, means a rule change (say, the tax rate becomes 10%) is a one-line fix. A number that appears in code with no explanation, like * 8 / 100, is called a magic number; good programmers replace magic numbers with named constants.

Practice 3.13

Fill in the blank

Fill in the blank with the name of the constant.

SPEED_LIMIT = 50
speed = 64
print("Over the limit by", speed - )

The finished program prints:

Target

Over the limit by 14

3.14 The shell's underscore

In the interactive shell only, the name _ (a single underscore) holds the last value the shell displayed. It's handy as a calculator:

>>> 1250 * 12
15000
>>> _ * 0.18
2700.0
>>> _ + 15000
17700.0

Each _ refers to the result just above it. This works only in the shell; in a script, _ isn't set up automatically.

Practice 3.14

Multiple choice

In the interactive shell, what does the name _ (a single underscore) hold?

Choose one answer

3.15 What happens in memory

+ 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

Explain in your own words the two steps Python takes to run total = price * 2.

Show the answer

First it works out the right side, price * 2, using the current value of price. Then it attaches the name total to that result.

Check yourself

Why is x = x + 1 sensible in Python but nonsense in maths?

Show the answer

In Python, = is an action, not a statement of fact. Python works out x + 1 using the old value of x, then makes x refer to the new value.

Check yourself

What's the difference between print(city) and print("city")?

Show the answer

print(city) looks up the variable city and prints its value. print("city") prints the four letters city.

Check yourself

Which of these are valid names? _temp, 3d_model, model3d, my.name, True, true, total-cost, कुल.

Show the answer

Valid: _temp, model3d, true (it's not the keyword True, but it's a confusing choice), कुल (valid, but stick to English names). Invalid: 3d_model (starts with a digit), my.name (contains .), True (keyword), total-cost (contains -).

Check yourself

After a = 7, b = a, a = 9, what is b? Explain using the label picture.

Show the answer

b is 7. b = a tied the label b to the object 7. a = 9 moved only the a label to a new object, 9; the b label is still on 7.

Check yourself

What does "dynamic typing" mean? Give one advantage and one disadvantage.

Show the answer

Names have no fixed type; the type belongs to whatever value the name currently refers to. Advantage: quick to write, no declarations. Disadvantage: type mistakes only show up when that line actually runs.

Check yourself

Why is type = "admin" a bad idea? What error might you see later?

Show the answer

It hides the built-in type function. Any later type(...) call fails with TypeError: 'str' object is not callable.

Check yourself

What is wrong with this swap, and how do you fix it in one line?

x = b
y = a
Show the answer

Assuming the goal is to swap a and b, after the first line both names refer to the same value and the other value is lost. Fix: a, b = b, a.

Check yourself

What does count += 1 mean? What happens if count was never assigned?

Show the answer

It means count = count + 1. If count was never assigned, you get NameError, because Python can't read a value that doesn't exist.

Check yourself

Python can't lock a constant. How do programmers mark a value as one?

Show the answer

By writing the name in UPPER_CASE, such as TAX_RATE.

Predict the output

Predict the output

x = 4
y = x * 2
x = 10
print(x, y)

Predict the output

a, b, c = 1, 2, 3
a, b, c = c, a, b
print(a, b, c)

Predict the output

n = 5
n *= 2
n -= 3
n **= 2
print(n)

Predict the output

value = 10
value = "ten"
value = value * 2
print(value)

Fix the bug

Fix the bug

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

Example run

450

Fix the bug

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

Example run

99

Fix the bug

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

Example run

7

Fix the bug

This should print Maya Leo and then Leo Maya.

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

Example run

Maya Leo
Leo Maya

Coding problems

Write code · Easy

Profile card. Store your name, city and age in three variables, then print them with labels, one per line.

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

Show the book's answer
name = "Alex"
city = "Tokyo"
age = 21
print("Name:", name)
print("City:", city)
print("Age:", age)

Output

Name: Alex
City: Tokyo
Age: 21

Write code · Easy

Rectangle. Store a rectangle's length (12.5) and width (8) in variables. Print its area and its perimeter.

Print the area first, then the perimeter.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Area: 100.0
Perimeter: 41.0

Write code · Easy

Fever check. Store a body temperature in Celsius (38.2). Convert it to Fahrenheit with F = C × 9 ÷ 5 + 32 and print both.

Print the temperature in Celsius first, then the temperature in Fahrenheit.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Celsius: 38.2
Fahrenheit: 100.76

Write code · Medium

Rotate three. Start with a = "red", b = "green", c = "blue". In one line, rotate them so that a gets b's value, b gets c's, and c gets a's. Print all three.

Print the three values on one line with one print, in the order a, b, c, with commas between the names.

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

Example run

green blue red

Write code · Medium

Shop bill with constants. Using constants PEN_PRICE = 2, NOTEBOOK_PRICE = 5 and TAX_RATE = 8, and variables for quantities (5 pens, 2 notebooks), print the subtotal, the tax and the total.

Print the subtotal first, then the tax, then the total. The tax is the subtotal times the rate, divided by 100.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Subtotal: 20
Tax: 1.6
Total: 21.6

Write code · Medium

Trace it. Write the trace table for this program (the value of each variable after each line), then run it to check your last row.

After the last line of the program, add print(x, y). The check reads these two numbers.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

5 10

Write code · Hard

Interest calculator. For a principal of $10,000 at 7.5% per year for 3 years, print the simple interest (P × R × N ÷ 100) and the final amount with compound interest (P × (1 + R ÷ 100)ᴺ). Use variables for P, R and N, so that changing one line updates everything.

Print the simple interest first, then the final amount with compound interest. Do not round the results.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Simple interest: 2250.0
Amount with compound interest: 12422.968749999998

Write code · Hard

Fibonacci without loops. The Fibonacci sequence starts 0, 1, and each next number is the sum of the two before it. Using just two variables a and b, the multiple-assignment line a, b = b, a + b, and print, print the first eight Fibonacci numbers.

Print the eight numbers in order, each with its own print.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

0
1
1
2
3
5
8
13

Write code · Hard

Shadow hunter. This program crashes. Explain exactly why, then fix it so it prints Total: 60 and then Largest: 30. (sum and max are built-in functions; you only need to know that max(10, 20, 30) gives the largest of its arguments.)

Start from the program in the question. The fixed program prints exactly two lines: Total: 60 and then Largest: 30.

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

Example run

Total: 60
Largest: 30

Chapter project: League scoreboard

Project

Keep the score of a small league. Two teams, Red and Blue, play three games. A win gives 3 points. A draw gives 1 point to each team. Write a program that follows these steps:

  1. Create two constants, WIN_POINTS and DRAW_POINTS, at the top of the program.
  2. Create two variables, red and blue, and start both at 0 with one chained assignment.
  3. Game one: Red wins. Game two: a draw. Game three: Red wins. Update the points with += and the constants, never with the plain numbers. After each game, print one line with the points of Red first and the points of Blue second.
  4. The referee then reports that the two columns of the score sheet were mixed up. Swap the two totals in one line, and print them again, Red first.
  5. On the last line, print the total number of points that the two teams have together.

The program prints five lines. No number other than 0 appears below the two constants.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Game one: 3 0
Game two: 4 1
Game three: 7 1
Corrected: 1 7
Points in total: 8