Skip to content
wannacode

Variables and types

Problem

The price is in three places

In an online shop one price shows up in several places: in the catalog, in the cart and at checkout. If it is written as a number everywhere, here is what happens:

print("Headphones: €49.90")
print("In the cart: headphones, €49.90")
print("To pay: €49.90")

Tomorrow the headphones are on sale. You have to find and fix every 49.90. Miss one, and the customer sees two different prices.

The idea

A variable: a name for a value

Write the price once and give it a name. Then write the name everywhere.

price = 49.90
print(f"Headphones: €{price}")
print(f"In the cart: headphones, €{price}")
print(f"To pay: €{price}")
Output
Headphones: €49.9
In the cart: headphones, €49.9
To pay: €49.9

price = 49.90 creates a variable: a name (price) under which the program keeps a value (49.90). Wherever the code says price, the program takes the value from there. You do not write the type: Python sees it from the value. The next card is about types.

f in front of the quotes makes an f-string: text where you write a value right inside curly braces, {price}. When it prints, the value comes out in that place.

The zero at the end disappeared: 49.90 came out as 49.9. For the number it is the same thing. You will see how to show the price with two digits after the decimal point in the lesson on input and output.

More precisely, if you are curious
  • A name starts with a letter and has no spaces. Write it in lowercase, and join the words with an underscore: price, price_per_night. Uppercase and lowercase letters matter: price and Price are two different names.
  • The language also allows names with letters outside English (café), but do not do it. Code all over the world uses plain Latin names, and that is how your colleagues will write too.
  • A name you have not given a value yet cannot be used. Python stops with NameError: name 'total' is not defined when it reaches that line.
  • Text and a number are not glued together with +:
stock = 12
print("In stock: " + stock + " items")
Output
TypeError: can only concatenate str (not "int") to str

Python keeps track of the type of values and does not turn the number into text by itself. That is why we write an f-string. If you want +, turn the number into text: "In stock: " + str(stock) + " items".

The idea

Kinds of values

The type says what the variable can hold. Here are the main ones:

name = "Backpack"
price = 39.90
stock = 12
on_sale = True
size = "M"
print(f"{name}, size {size}")
print(f"Price: €{price}")
print(f"In stock: {stock} items")
print(f"On sale: {on_sale}")
Output
Backpack, size M
Price: €39.9
In stock: 12 items
On sale: True
  • int: a whole number, for example a count.
  • float: a decimal number, for example a price or a weight. In code the decimal separator is a point: 39.90.
  • bool: yes or no, True or False, with a capital letter.
  • str: text, in quotes: "Backpack". This is a string, a sequence of characters. There is no separate type for one character: "M" is text of length 1.

type(...) tells you the type of a value. If you add these lines to the same program:

print(type(name))
print(type(price))
print(type(stock))
print(type(on_sale))
print(type(size))
Output
<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>
<class 'str'>
More precisely, if you are curious

In Python int has no limit: a whole number can have as many digits as you want, and math with it is exact. float is like double in Java and C#: a decimal number in 8 bytes, with about 15 to 16 significant digits. Underscores between digits only make it easier to read:

population = 8_100_000_000
weight = 1.5
huge = 123_456_789_012_345_678_901_234_567_890
print(f"{population} {weight}")
print(huge + 1)
Output
8100000000 1.5
123456789012345678901234567891

float stores numbers in binary, and some decimal values like 0.1 do not come out exactly: 0.1 + 0.2 is 0.30000000000000004. For money, real programs use Decimal from the decimal module. In this course, to keep it short, we write prices as float.

Try it

Find the bug

The program should print "Notebook: 3 x €2.4". It runs, but it prints "Notebook: 3 x €(2, 40)". Which line is the bug on?

Pick the line with the bug.

The idea

= stores a copy

The = sign is not "equals" as in math. It means: take the value on the right and store it in the variable on the left. This is called assignment. The variable's old value is gone.

When there is another variable on the right, a copy of its value at that moment is stored. The two variables do not stay connected:

seats = 40
seats_at_start = seats
seats = 37
print(f"At the start: {seats_at_start}")
print(f"Now: {seats}")
Output
At the start: 40
Now: 37

seats_at_start gets 40. Then seats becomes 37, but the copy in seats_at_start stays 40.

More precisely, if you are curious

To be precise: in Python = does not make a copy. It gives seats_at_start the same value, 40. When later seats = 37, seats gets a new value, and seats_at_start stays with 40. For numbers and text this behaves exactly like a copy. The difference shows up with lists.

Try it

Which value stays?

What will the program print?

room_a = 12
room_b = 20
room_a = room_b
room_b = 25
print(f"{room_a} and {room_b}")
Answer

Problem

The sizes are swapped

A photo printing program gets the sizes swapped: width 120 and height 80, when they should be 80 x 120. It looks like you just need to store one in the other and back again:

width = 120
height = 80
width = height
height = width
print(f"{width} x {height}")
Output
80 x 80

You got 80 x 80. Where did 120 go?

See it

Swapping with a helper variable

width = 120
height = 80
temp = width
width = height
height = temp
print(f"{width} x {height}") # 80 x 120
Step by step, in words
  1. The width and the height were entered swapped: 120 and 80.
  2. temp = width: a copy of 120 goes into temp. width still holds 120.
  3. width = height: a copy of 80 goes into width. The old 120 is gone from there, but it is saved in temp.
  4. height = temp: 120 comes back from temp into height.
  5. They are swapped: 80 x 120.

In the naive version, width = height stores 80 in width, and the old 120 is gone. When height = width comes next, width already holds 80, and that is copied back.

The fix is a third, helper variable, temp. It keeps 120 before width is overwritten. Then 120 goes from temp into height, and the sizes come out 80 x 120.

More precisely, if you are curious
In Python the swap can also be written on one line. On the right, both values are taken at once, and only then are they stored on the left:
width = 120
height = 80
width, height = height, width
print(f"{width} x {height}")
Output
80 x 120

You will see it in other people's code. Here we write it with temp, so you can see what happens step by step.

Try it

Put the swap in order

At the shop, two coworkers trade shifts. morning is "Ivan", and evening is "Maria". Put the lines in order so they swap.

  1. print(f"Morning: {morning}, evening: {evening}")
  2. evening = temp
  3. morning = evening
  4. temp = morning

The idea

The type belongs to the value

In Python you do not write the type of the variable. It belongs to the value: 3 is an int, "three" is a str. That is why the same variable can later get a value of another type:

nights = 3
print(type(nights))
nights = "three"
print(type(nights))
Output
<class 'int'>
<class 'str'>

Python does not complain. This is called dynamic typing: the type is known only while the program runs. It is handy, but it also easily leads to bugs: if nights is a number in one place and text in another, math with it will stop. Keep one kind of value in one variable.

More precisely, if you are curious

You can write the type as a note: nights: int = 3. This is called a type annotation. Python does not check it, and nights = "three" after it still goes through. Separate programs like mypy check it. We do not use them in this course.

Exercise

Your variables

Solve the tasks in your editor. The values are written in the code, with no reading from the keyboard. Reading is in the next lesson.

1. Swap. The top shelf has 15 books, the bottom one 27. Store them in two variables, swap their values and print before and after.

Output
Before: top 15, bottom 27
After: top 27, bottom 15

2. Age. Store a name and an age in two variables and print them in a sentence.

Output
Maria is 19 years old.

3. A hotel card. Store in variables the name of the hotel (text), the stars (a whole number), the rating (a decimal), whether there is breakfast (yes or no) and the category (one character). Print them.

Output
Hotel: Sea Star
Stars: 4
Rating: 8.7
Breakfast: True
Category: B

More tasks

  • Three in a circle. Three cash registers start the day with €120, €85 and €240. Move the amounts in a circle: the first goes into the second, the second into the third, the third into the first. Use one helper variable. Print 240 120 85.
  • The types. Print the type of each value from task 3 with type().
  • An error on purpose. Glue text and a number with +: print("Stars: " + stars). Read what Python says. Then write the rating with a comma, rating = 8,7, and see what gets printed.

Test

Check yourself

1. What does the line count = 5 do?
2. What is the type of 12.99 in Python?
3. a = 5, b = a, a = 9. What is b?
4. Why does swapping two values need a third variable?
5. nights = 3, then nights = "three". What happens?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·