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:
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.
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=21age=age+1print(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
total=price*4
total=total+3
print("Total with delivery:",total)
price=6
The right side of an assignment is worked out first, so every name on the right side must exist already.
total must be created before the line that uses total on its right side.
price=6total=price*4total=total+3print("Total with delivery:",total)
Each assignment works out its right side with the current values, so price comes first, then the first total, then the update.
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
Output
You need three assignment lines and one print line.
The right side of the third assignment is pizzas * slices_each.
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
Output
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=10print(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")
Look at the second line. Is the word inside quotes?
Quotes mean text, exactly as written. Python looks up a name only when there are no quotes.
The answer is: city
With quotes, "city" is four letters of text. Without quotes, city would be a name, and Python would look up its value.
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
Output
Read the name in the error message letter by letter. Compare it with the name on the first line.
Capitals matter: Score and score are two different names.
score=40bonus=5print("Final score:",score+bonus)
The program defined score but referenced Score. Python has never heard of Score, so it raises a NameError.
Multiple choice
What happens when this program runs?
width=4print(width*height)height=3
Python runs the lines from top to bottom, one by one.
When line 2 runs, has line 3 created height yet?
The answer is: It stops with a NameError
A name must be defined before it is referenced. Line 2 uses height before line 3 creates it, so Python stops with a NameError.
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.
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=5b=aa=10b=b+aprint(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=2y=xx=7y=y+xprint(x,y)
y = x gives y the value that x has at that moment. After that, y does not follow x.
Before line 4 runs, x is 7 and y is still 2.
It prints
7 9
Line 3 changes x only. Line 4 then works out 2 + 7 and attaches y to the result.
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
level=1
level=level+1
print("Start level:",level)
print("Next level:",level)
A variable must be created before any line uses it.
Each print shows the value that level has at that moment, so the first print must run before the update.
The same name is printed two times with two different values, because an assignment between the two print lines changed it.
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:
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.
After y = x, two names refer to one object. One object has one identity.
x = 2000 moves the name x to a new object. The name y stays on the old one.
It prints
True
False
Two names for one object give the same identity. After x is assigned again, the two names refer to two different objects.
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:
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=3data="three"data=3.5print(type(data))
A name has no type of its own. The type belongs to the value.
Which value does data refer to when the last line runs?
The answer is: <class 'float'>
With dynamic typing, one name can refer to values of different types. type() reports the type of the current value.
3.7 Rules for names
A name (programmers also say identifier) must follow these rules:
It can contain letters, digits and underscores (_).
It can't start with a digit.
It can't contain spaces or symbols like -, @, $, . or !.
It can't be a keyword (see below).
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:
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:
firstname="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.
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?
A name can contain letters, digits and underscores only.
A digit is fine, but not as the first character.
The answer is: runner_3
runner_3 uses only letters, an underscore and a digit that is not at the start. The others start with a digit, contain a minus sign, or contain a space.
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
Output
One name contains a space. The other name starts with a digit.
Join words with an underscore, and start the second name with a letter. Change every place where each name is used.
A name cannot contain a space and cannot start with a digit. Underscores join the words of a name.
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?
All four names are allowed by Python. The question is about the habit that Python programmers agree on.
Capitals with underscores are for constants. Variables use lowercase words joined by underscores.
The answer is: total_marks
Variables use snake_case: lowercase words joined by underscores. UPPER_SNAKE_CASE is for constants and CapWords is for classes.
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"delprintprint("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'>
Output
After the first line, what does the name type refer to?
Choose a different name for the variable, such as user_type, on the first two lines.
user_type="student"print("Kind of user:",user_type)print(type(4.5))
Assigning to type hides the built-in function. With a different variable name, type(4.5) reaches the built-in again.
3.10 Several assignments at once
Multiple assignment
You can assign several names in one line by separating both sides with commas:
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=0print(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=1b=2a=bb=aprint(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=1b=2temp=aa=bb=tempprint(a,b)
Output
2 1
In Python, multiple assignment does it in one line:
a=1b=2a,b=b,aprint(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.
Without temp, the first value is lost as soon as left is assigned again. temp keeps a label on it until right takes it.
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
Output
Multiple assignment can give two names new values in one line.
Write the two names on the left of =, and the same two names in the opposite order on the right.
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=10coins5print(coins)
The finished program prints:
Target
15
The long form of the line is coins = coins + 5.
The shorthand puts the arithmetic operator directly before the = sign.
coins=10coins+=5print(coins)
coins += 5 means exactly coins = coins + 5.
Predict the output
What does it print?
stock=20stock-=5stock*=2stock+=1print(stock)
Write each line in its long form, for example stock = stock - 5.
Each line starts from the value that the line before it left in stock.
It prints
31
Each augmented assignment updates stock from its own current value, one line after the other.
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
Output
visitors += 1 means visitors = visitors + 1. What value does the right side read on the first line?
Start the count before you add to it: put visitors = 0 at the top.
Augmented assignment reads the old value first, so the variable must exist already. Start the count at 0.
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
Output
Create the variable first with steps = 0. After that, each update is one line.
Put a print line after each of the three updates. Doubling is steps *= 2.
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.
del removes a name tag. Is another tag still tied to the object?
The name second still refers to 30 after the del line. Then 5 is added.
It prints
35
del first removes only the name first. The object still has the name second, so the program can go on using it.
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.
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=50speed=64print("Over the limit by",speed-)
The finished program prints:
Target
Over the limit by 14
The limit is stored once at the top, under a name written in capitals.
Capitals matter. Write the name exactly as on the first line.
SPEED_LIMIT=50speed=64print("Over the limit by",speed-SPEED_LIMIT)
A named constant replaces a magic number. If the limit changes, only the first line needs a change.
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:
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?
Look at the shell session in this section. Each _ stands for the result just above it.
It works like the memory key of a calculator.
The answer is: The last value the shell displayed
In the shell, _ refers to the last value that was displayed. In a script it is not set up automatically.
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=4y=x*2x=10print(x,y)
Trace the program line by line. What is x at the moment when y is worked out?
Changing x later does not work out y again. Only an assignment to y can change y.
It prints
10 8
y was calculated when x was 4. Changing x later doesn't recalculate y.
x=4y=x*2x=10print(x,y)
Output
10 8
Predict the output
a,b,c=1,2,3a,b,c=c,a,bprint(a,b,c)
Python finishes the whole right side before it attaches any name.
Write down the values of c, a and b first. Then give them to the names on the left, in order.
It prints
3 1 2
The right side c, a, b is 3, 1, 2, worked out before any names change.
a,b,c=1,2,3a,b,c=c,a,bprint(a,b,c)
Output
3 1 2
Predict the output
n=5n*=2n-=3n**=2print(n)
Each line uses the value that the line before it left in n.
n *= 2 means n = n * 2, and n **= 2 means n = n ** 2, which is n times n.
It prints
49
5 → 10 → 7 → 49.
n=5n*=2n-=3n**=2print(n)
Output
49
Predict the output
value=10value="ten"value=value*2print(value)
After the second line, what type of value does value refer to?
You saw in Chapter 2 that text times a number repeats the text.
It prints
tenten
Dynamic typing: value ends up as a string, and * repeats text.
value=10value="ten"value=value*2print(value)
Output
tenten
Fix the bug
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
450
Output
Read the rules for names in section 3.7. Which character is not allowed inside a name?
Join the two words with an underscore, on both lines.
total_marks=450print(total_marks)
Names can't contain spaces (SyntaxError). Use an underscore.
total_marks=450print(total_marks)
Output
450
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
99
Output
Python runs the file from top to bottom. Which line creates the name?
A name must be defined before it is referenced. Change the order of the two lines.
price=99print(price)
The name is used before it's assigned (NameError). Swap the lines.
price=99print(price)
Output
99
Fix the bug
The program prints the lines below. Your program must print exactly these lines.
Example run
7
Output
After the first line, what does the name max refer to?
Give the two variables names that are not built-in names. Then max(3, 7) can reach the built-in function.
max_marks=100min_marks=0print(max(3,7))
max = 100 hides the built-in max function, so max(3, 7) tries to call the number 100 (TypeError: 'int' object is not callable). Rename the variables.
max_marks=100min_marks=0print(max(3,7))
Output
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
Output
After first = second, which value do both names refer to? Where did the other value go?
Swap the two values in one line with multiple assignment.
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
Output
Python works out the whole right side before any name changes, so one line with three names on each side is enough.
On the left write the names that receive. On the right write, in the same order, the name whose value each one gets.
a="red"b="green"c="blue"a,b,c=b,c,aprint(a,b,c)
a="red"b="green"c="blue"a,b,c=b,c,aprint(a,b,c)
Output
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
Output
Write the three constants at the top. Then make two variables for the quantities.
The subtotal is pens times the pen price plus notebooks times the notebook price. Store it, then work out the tax from it.
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
Output
Make a table with one row per line and one column for each variable.
For each line, work out the right side with the values of the row above. On the last line, both values on the right are read before any name changes.
x=3y=x+2x=y*2y=x-yx,y=y,xprint(x,y)
After line
x
y
x = 3
3
—
y = x + 2
3
5
x = y * 2
10
5
y = x - y
10
5
x, y = y, x
5
10
x=3y=x+2x=y*2y=x-yx,y=y,xprint(x,y)
Output
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
Output
Make three variables for the principal, the rate and the number of years. Use only these names in the two formulas.
The power operator is **, so the compound amount is P * (1 + R / 100) ** N.
P=10_000R=7.5N=3simple_interest=P*R*N/100compound_amount=P*(1+R/100)**Nprint("Simple interest:",simple_interest)print("Amount with compound interest:",compound_amount)
Notice the compound-interest answer has a long tail of digits: that's float rounding (Chapter 2). You'll learn to show just two decimal places in → Chapter 16.
P=10_000R=7.5N=3simple_interest=P*R*N/100compound_amount=P*(1+R/100)**Nprint("Simple interest:",simple_interest)print("Amount with compound interest:",compound_amount)
Output
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
Output
Start with a, b = 0, 1 and print a.
After each a, b = b, a + b, the name a holds the next number of the sequence. Print it, then repeat the two lines.
The same line repeated seven times is crying out for a loop → Chapter 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
Output
After the line max = max(a, b, c), what does the name max refer to?
Choose names that are not built-in names for the total and for the largest value. The last line is then no longer needed.
sum = ... hides the built-in sum, which is harmless here because sum is never called. But max = max(a, b, c) works once and then replaces the max function with the number 30. The next max(1, 2) tries to call 30, giving TypeError: 'int' object is not callable. Fix: use names that aren't built-ins.
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:
Create two constants, WIN_POINTS and DRAW_POINTS, at the top of the program.
Create two variables, red and blue, and start both at 0 with one chained assignment.
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.
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.
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
Output
Constants are ordinary variables with names in capitals. red = blue = 0 gives both names the same starting value.
A win is red += WIN_POINTS. A draw needs two lines, one for each team, with DRAW_POINTS.
The swap is one multiple assignment: both names on the left, and the same names in the opposite order on the right. The last line prints red + blue.
WIN_POINTS=3DRAW_POINTS=1red=blue=0red+=WIN_POINTSprint("Game one:",red,blue)red+=DRAW_POINTSblue+=DRAW_POINTSprint("Game two:",red,blue)red+=WIN_POINTSprint("Game three:",red,blue)red,blue=blue,redprint("Corrected:",red,blue)print("Points in total:",red+blue)
The program uses constants in place of magic numbers, a chained assignment to start both counts, augmented assignment to update them, and multiple assignment to swap them.