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.90print(f"Headphones: €{price}")print(f"In the cart: headphones, €{price}")print(f"To pay: €{price}")Headphones: €49.9In the cart: headphones, €49.9To pay: €49.9price = 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:priceandPriceare 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 definedwhen it reaches that line. - Text and a number are not glued together with
+:
stock = 12print("In stock: " + stock + " items")TypeError: can only concatenate str (not "int") to strPython 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.90stock = 12on_sale = Truesize = "M"print(f"{name}, size {size}")print(f"Price: €{price}")print(f"In stock: {stock} items")print(f"On sale: {on_sale}")Backpack, size MPrice: €39.9In stock: 12 itemsOn sale: Trueint: 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,TrueorFalse, 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))<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_000weight = 1.5huge = 123_456_789_012_345_678_901_234_567_890print(f"{population} {weight}")print(huge + 1)8100000000 1.5123456789012345678901234567891float 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.
2,40 is two numbers, 2 and 40, written together as a pair (such a pair is called a tuple). There is no error, so you catch a slip like this by looking at the output. The price is price = 2.40.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 = 40seats_at_start = seatsseats = 37print(f"At the start: {seats_at_start}")print(f"Now: {seats}")At the start: 40Now: 37seats_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 = 12room_b = 20room_a = room_broom_b = 25print(f"{room_a} and {room_b}")room_a = room_b stores a copy of 20 in room_a. When room_b later becomes 25, room_a does not change.
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 = 120height = 80width = heightheight = widthprint(f"{width} x {height}")80 x 80You got 80 x 80. Where did 120 go?
See it
Swapping with a helper variable
width = 120height = 80temp = widthwidth = heightheight = tempprint(f"{width} x {height}") # 80 x 120Step by step, in words
- The width and the height were entered swapped: 120 and 80.
- temp = width: a copy of 120 goes into temp. width still holds 120.
- width = height: a copy of 80 goes into width. The old 120 is gone from there, but it is saved in temp.
- height = temp: 120 comes back from temp into height.
- 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
width = 120height = 80width, height = height, widthprint(f"{width} x {height}")80 x 120You 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.
print(f"Morning: {morning}, evening: {evening}")evening = tempmorning = eveningtemp = 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 = 3print(type(nights))nights = "three"print(type(nights))<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.
Before: top 15, bottom 27After: top 27, bottom 152. Age. Store a name and an age in two variables and print them in a sentence.
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.
Hotel: Sea StarStars: 4Rating: 8.7Breakfast: TrueCategory: BMore 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