Values and Variables
Every program works with pieces of data: a number of points, a price, a word someone typed. Python calls each piece a value, and every value has a type that decides what can be done with it. Once you know the type of each value and the name it is stored under, you can look at a line that prints values and say what it will show before you run it.
Values and their types
A value is one piece of data a program works with. When you write 42 in a Python file, Python reads it as the number forty-two. When you write "hello" between quotes, Python reads it as a piece of text. Both are values, but they are different kinds of value, and Python keeps track of which kind each one is. That kind is called the value's type.
Three types cover most of what a first program needs:
- Whole numbers, such as
3,0or-12. Python calls this typeint, short for integer. - Decimal numbers, numbers with a decimal point, such as
4.5or0.25. Python calls this typefloat, short for floating-point number. - Text, written between single quotes
'...'or double quotes"..."(both give the same result). Python calls a piece of text a string, and the typestr.
The way a value is written decides its type. A number with a decimal point is always a float, even when its value is whole, so 5.0 is a float and 5 is an int. And anything between quotes is a string, even when it looks like a number: "5" is a piece of text made of one character.
| Written in the code | Type | What it is |
|---|---|---|
| 42 | int | a whole number |
| 4.5 | float | a decimal number |
| 5.0 | float | a decimal number, because of the point |
| "hello" | str | a string of text |
| "5" | str | text that happens to be a digit |
When you are not sure, Python can tell you. type(42) gives back the type of the value. Printing it shows <class 'int'>, where class is the word Python uses in this message for a type. For 4.5 it shows <class 'float'>, and for "hello" it shows <class 'str'>.
True or false?
"7" and 7 are the same value in Python.
False. The quotes make "7" a string, a piece of text. Without quotes, 7 is an int, a whole number. They have different types.
10.0 is a float, even though its value is a whole number.
True. A number written with a decimal point is always a float. The point decides the type, not whether anything comes after it.
Why the type decides what you can do
The type matters because Python looks at it to decide what an operation means. The plus sign is a good example. Between two numbers, + adds them. Between two strings, + glues them together into one longer string. The symbol is the same, but the types of the values around it decide what happens.
print(3 + 4)
print("3" + "4")
print("ice" + "cream")7
34
icecreamThe second line shows 34, not 7: those are two strings, so Python joined the character 3 and the character 4. Notice also that print shows a string without its quotes. The quotes only tell Python where the text starts and ends.
When the two sides have types that do not fit together, Python refuses and stops the program with an error. Adding a string and a number is one such case:
print("Points: " + 3)TypeError: can only concatenate str (not "int") to strThe message names the problem: concatenate means glue together, and Python can only glue a string to another string, not to an int. Python never guesses whether you meant to do arithmetic or to build text. You decide, by turning the value into the type you need, which is the next idea.
True or false?
"2" + "2" gives "22".
True. Both values are strings, so + glues them together. To get 4, both sides have to be numbers.
Python turns 3 into text by itself when you write "Points: " + 3.
False. Python stops with a TypeError instead. It does not change a type for you; you convert the value yourself.
Converting a value to another type
Python has a converter named after each type. You write the type's name, then the value in round brackets, and you get back a new value of that type. The original value stays as it was.
| You write | You get | What happened |
|---|---|---|
| int("42") | 42 | text with digits became a whole number |
| float("2.5") | 2.5 | text became a decimal number |
| str(42) | "42" | a number became text |
| int(3.9) | 3 | the decimal part was cut off, not rounded |
| float(7) | 7.0 | a whole number became a decimal number |
With converters, both earlier problems go away. int("3") + int("4") adds two numbers and gives 7, and "Points: " + str(3) glues two strings and gives Points: 3.
Two details catch people out. First, int() of a decimal number throws away everything after the point: int(3.9) is 3, not 4. Rounding is a separate step, explained further down. Second, a converter only works when the text really is a number of that kind. int("hello") stops the program with a ValueError. So does int("3.5"), because int() expects text that shows a whole number. For text with a decimal point, float("3.5") works.
True or false?
int(7.8) gives 8.
False. int() cuts off the decimal part, so int(7.8) gives 7. Use round() when you want the nearest whole number.
str(15) + " points" gives the text 15 points.
True. str(15) turns the number into the string "15", and + then glues two strings together.
Variables: names for values
A value written straight into a line is used once and then gone. To use it again, you give it a name. A variable is a name that refers to a value. You create one with an equals sign: the name on the left, the value on the right.
price = 4.5
count = 3
total = price * count
print(total)13.5This is called assignment. Python works out the right side first, then attaches the name on the left to the result. On the third line it looks up the values of price and count, multiplies them, and makes the name total refer to 13.5. From then on, writing total anywhere means that value.
The equals sign here is not the equals of a maths lesson. It does not state that two things are equal; it is an instruction: make this name refer to this value. That is why the name always goes on the left.
A variable can be reassigned: a later assignment to the same name makes it refer to a new value, and the old value is no longer reachable by that name. The right side may even use the name's current value.
score = 3
score = score + 2
print(score)- score
- 3
- 5
- first line
- after line 2
Read the second line from the right: Python first computes score + 2 with the current value, 3, which gives 5, and then moves the name score to the new value. The program prints 5. Lines run from top to bottom, so to know what a name means at a given line, follow its assignments down to that line.
A name has to be assigned before it is used. If a line uses a name that no assignment created, for example because of a typing mistake such as scor instead of score, Python stops with a NameError whose message says the name is not defined.
True or false?
After the lines x = 10 and then x = x * 2, the name x refers to 20.
True. Python computes x * 2 with the current value 10, gets 20, and then makes x refer to that new value.
In a = 5 then b = a then a = 9, the name b refers to 9 at the end.
False. b = a made b refer to the value 5. Moving the name a to 9 later does not move b, so b still refers to 5.
Choosing names, and leaving notes with comments
Python has a few rules for names. A name is made of letters, digits and the underscore _, and it cannot start with a digit, so answer_2 is a valid name and 2nd_answer is not. A name cannot contain a space. Capital and small letters count as different, so Score and score are two separate names. A small set of words that Python reserves for itself, such as if, for and True, cannot be used as names.
Within those rules, choose a name that says what the value is. Compare t = p * c with total = price * count: both run the same way, but only the second tells a reader what is being calculated. Python's style guide writes variable names in small letters with underscores between the words, such as correct_answers, and advises against the single letters l, O and I, which are easy to mistake for the digits one and zero.
Sometimes a name alone cannot say why a line is there. For that, you write a comment: a note for the person reading the code. A comment starts with the hash character # and runs to the end of the line. Python skips it completely, so a comment never changes what the program does.
# Prices are in euros, taken from the shop's list.
price = 4.5
count = 3 # three items in the basket
print("Use # to start a comment")A comment can stand on its own line or after the code on a line. A # inside quotes is different: it is part of the string, so the last line prints Use # to start a comment in full. A useful comment says something the code does not already say. A note such as # add 2 to score next to score = score + 2 only repeats the line, while a note that explains why the 2 is added helps the next reader.
True or false?
total_price and Total_price are the same variable.
False. Python treats capital and small letters as different, so these are two separate names.
Deleting every comment from a program leaves what it prints unchanged.
True. Python skips comments, so they never affect what the program does. A # inside quotes is not a comment, though: it is part of the string.
Calculating with numbers
Python calculates with the symbols you know from a calculator, called operators. They work on ints and floats, and on variables that refer to them.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | add | 7 + 2 | 9 |
| - | subtract | 7 - 2 | 5 |
| * | multiply | 7 * 2 | 14 |
| / | divide | 7 / 2 | 3.5 |
| / | divide | 6 / 3 | 2.0 |
Multiplication uses *, not a cross, and division uses /. As in maths, * and / are done before + and -, and round brackets change the order: 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20.
Look at the last row of the table. Division with / always gives a float, even when the result is whole: 6 / 3 is 2.0, not 2. Python does this so that the type of the result never depends on whether the numbers happen to divide evenly. When you print it, you see the .0, which is the sign that the value is a float. (When you need a whole-number result, Python has a separate operator, //, which divides and drops the remainder: 7 // 2 is 3.)
The same thing happens when an int and a float meet in one calculation: Python turns the int into a float first, so the result is a float. 3 + 2.0 is 5.0, and 4 * 2.5 is 10.0. Adding, subtracting or multiplying two ints gives an int.
One calculation has no answer at all: dividing by zero. 5 / 0 stops the program with a ZeroDivisionError.
True or false?
print(10 / 5) shows 2.
False. Division with / always gives a float, so it shows 2.0.
print(3 * 2.0) shows 6.0.
True. One side is a float, so Python calculates with floats and the result is the float 6.0.
Rounding a result
Division often gives more digits than you want to show: 10 / 3 is 3.3333333333333335. The built-in round() gives back the number rounded, and how it rounds depends on what you put in the brackets.
| You write | You get | Type of the result |
|---|---|---|
| round(3.7) | 4 | int |
| round(3.14159, 2) | 3.14 | float |
| round(10 / 3, 1) | 3.3 | float |
| round(2.5) | 2 | int |
With one value, round() gives the nearest whole number, and the result is an int: round(3.7) is 4, not 4.0. With a second value, it keeps that many digits after the point and gives a float: round(3.14159, 2) is 3.14.
When a number lies exactly halfway, Python rounds to the even neighbour rather than always up. So round(2.5) is 2 and round(3.5) is 4. Over many numbers, this keeps the rounding from drifting upwards.
The 3.3333333333333335 above also shows that floats are not perfectly exact. A computer stores a float in binary, as ones and zeros, and most decimal fractions cannot be stored exactly that way. So a float holds a very close approximation of the number you wrote. This is not a mistake in your code. It is also the reason round(2.675, 2) gives 2.67: the stored number is a tiny bit below 2.675. For showing a result to a person, rounding to a few digits is the usual answer.
True or false?
round(8.6) gives 9.
True. With one value, round() gives the nearest whole number as an int, so the result is 9 (not 9.0).
round(0.5) gives 1, because halves are always rounded up.
False. Python rounds an exact half to the even neighbour, so round(0.5) gives 0 and round(1.5) gives 2.
Putting values into text with f-strings
Programs often need to show values inside a sentence. You could glue strings together with + and str(), but that gets long and easy to get wrong. Python has a shorter way: the f-string, a string with the letter f written just before its opening quote. Inside it, anything you write between curly brackets { } is not text but a piece of Python. When the line runs, Python works out each one and puts its value into the text at that place.
name = "Sam"
correct = 3
questions = 4
print(f"{name} answered {correct} of {questions} questions")
print(f"That is {correct / questions * 100} percent")
print(f"Wrong answers: {questions - correct}")
print("{name} answered")Sam answered 3 of 4 questions
That is 75.0 percent
Wrong answers: 1
{name} answeredTo predict a line like these, take the text as it is written and replace each pair of curly brackets with the value of what is inside. {name} becomes Sam, without quotes, exactly as print shows a string. The brackets may hold a small calculation, not only a name. {correct / questions * 100} is worked out first, and since it contains a division, the value is the float 75.0.
An f-string also needs no str(): Python turns each value into text by itself, which is why numbers and strings mix freely in it.
The f is what makes this happen. The last line has no f, so the curly brackets are ordinary characters and Python prints {name} as it stands. Forgetting the f is the most common f-string mistake, and the output shows it at once.
To control how a number looks, add a colon and a format after the value inside the brackets. :.2f shows a number with exactly two digits after the point: if total is 13.5, then f"{total:.2f} euros" gives 13.50 euros. Unlike round(), this changes only how the value is shown in the text; the variable keeps its value.
True or false?
If count is 4, print(f"{count * 2} cards") shows 8 cards.
True. Python works out count * 2, which is 8, and puts that value where the curly brackets were.
If count is 4, print("{count} cards") shows 4 cards.
False. Without the f before the quote this is an ordinary string, so it shows {count} cards, brackets and all.
If total is 9, print(f"{total / 3}") shows 3.
False. The calculation inside the brackets is a division with /, which always gives a float, so it shows 3.0.