Variables and Data Types
Storing values, the five types you need, and why the equals sign does not mean what it meant in maths.
Variables
name = "Aisha"
age = 14
height = 1.62
is_student = TrueThe equals sign is not equality. It means: work out the right hand side, then attach the name on the left to that value.
That is why this makes sense in programming but not in maths:
score = 10
score = score + 5 # work out 10 + 5, then make score refer to 15
print(score) # 15Naming rules
- Must start with a letter or underscore
- May contain letters, digits and underscores, but no spaces
- Case sensitive, so
Scoreandscoreare different - Cannot be a Python keyword such as
if,fororclass
Naming well
n = 25 # bad
num_students = 25 # good
d = 3.5 # bad
distance_km = 3.5 # goodPython convention is lower_case_with_underscores for variables and UPPER_CASE for constants.
Shortcuts
score += 10 # same as score = score + 10
lives -= 1 # same as lives = lives - 1
total *= 2 # same as total = total * 2- = stores a value in a variable: the name on the left, the value on the right.
- A variable is a labelled box with a name, a value and a data type.
- The value can change. age = age + 1 takes the 15 out and puts 16 in.
- A constant holds a value that must never change. By convention it is written in capitals.
- Names use letters, digits and underscores. No spaces, and no digit first.
Data types
| Type | Name | Example |
|---|---|---|
| Whole number | int | 42, -7, 0 |
| Decimal number | float | 3.14, -0.5 |
| Text | str | "hello", "42" |
| True or False | bool | True, False |
| Nothing | NoneType | None |
print(type(42)) # <class 'int'>
print(type("42")) # <class 'str'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>42 and "42" are completely differentOne is a number you can do arithmetic on. The other is text. 42 + 1 gives 43. "42" + "1" gives "421".
Converting between types
int("42") # 42
int(3.9) # 3, it cuts off rather than rounding
float("3.5") # 3.5
str(42) # "42"
bool(0) # False
bool(1) # True
round(3.7) # 4, this rounds properlyChoosing the right type
- A person's age:
int, because ages are whole numbers - A price:
float, because it needs pence - A phone number:
str, because it may start with 0 and you never do arithmetic on it - Whether the game is over:
bool, because there are only two states
If you would never add or multiply it, store it as a string. Postcodes, ID numbers, phone numbers and card numbers are all strings.
- Five data types: integer, real, Boolean, character and string.
- A phone number is a string: you never add them, and a number would lose the leading 0.
- Casting changes a value from one type to another: int(), str(), float().
- int() turns text into a whole number.
- int() on a float cuts off the decimals. It does not round.
- str() turns a number into text.
- float() turns text into a decimal number.
- input() always returns text, so convert it before doing sums.
- A conversion that does not make sense raises an error, so validate first.
Key terms you must be able to define
- Variable
- A name attached to a value that can change while the program runs.
- Assignment
- Giving a variable a value using the equals sign.
- int
- The whole number data type.
- float
- The decimal number data type.
- str
- The text data type, called a string.
- bool
- The data type holding only True or False.
- Casting
- Converting a value from one data type to another, such as int() or str().
- Constant
- A value that should not change, written in upper case by convention.
Flashcards
Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.
Reach the top grade on this topic
- Choose the correct data type for any piece of data and justify it
- Explain why
42 + 1and"42" + "1"give different results - Use
+=and-=correctly to update a running total - Name every variable so that someone reading your code needs no explanation
Mistakes that cost marks here
- Storing a phone number as an int, which removes the leading zero.
- Assuming int(3.9) rounds to 4. It truncates to 3. Use round() to round.
- Using a variable before assigning it a value, which gives a NameError.
- Naming variables x, y and z in a program with twenty of them.
In Python a variable is really a label attached to a value, not a box containing it. That is why two variables can point at the same list, and changing it through one changes what you see through the other.
Knowledge check
score = score + 5 do if score was 10?3.14?"5" + "3" give?int(7.9) give?score += 3 short for?type("42") return?Exam-style questions
Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.
- LAge is an integer
- LPrice is a float
- LPaid is a boolean
A student's age should be an integer, because ages are whole numbers and arithmetic is performed on them. A product price should be a float, because prices include pence and therefore need a decimal part. Whether an order is paid should be a boolean, because there are only two possible states and a boolean makes that meaning completely clear while using the least memory.
"10" + "5" gives a different result from 10 + 5.3 marks- LThe first pair are strings
- LThe plus operator joins strings together rather than adding
- LThe second pair are integers so the plus operator performs addition
In the first case both values are strings, because they are written inside quotation marks. When the plus operator is applied to two strings it concatenates them, joining them end to end, so the result is the string "105". In the second case both values are integers, so the plus operator performs ordinary numerical addition and the result is 15. This is why input from the user must be converted with int() before any arithmetic is done on it.
- LPhone numbers often begin with a zero
- LAn integer would discard the leading zero, changing the number
- LNo arithmetic is ever performed on a phone number
Phone numbers in the UK begin with a zero, and an integer stores only the numeric value with no record of leading zeros, so 07700900123 would be stored and displayed as 7700900123, which is not the correct number and would fail to match records held elsewhere. In addition, no arithmetic is ever carried out on a phone number, so there is no benefit at all to storing it as a number. A string preserves every character exactly as entered, which is what is needed.
- LInitialises the variable to 0
- LAdds 25 to it
- LPrints the result
score = 0 score += 25 print("Your score is", score) The variable is created and set to 0 first, which matters because a variable cannot be used before it exists. The += shortcut adds 25 to whatever the score currently is, and the print statement then displays the updated value.
int(4.8) and the programmer expects the result 5. Explain what actually happens and how to get the intended result.3 marks- Lint() removes the decimal part rather than rounding
- LThe result is therefore 4
- LUse round() to round to the nearest whole number
The int() function converts a value to a whole number by discarding everything after the decimal point rather than rounding, so int(4.8) gives 4 rather than 5. To round to the nearest whole number the programmer should use round(4.8), which correctly gives 5. This distinction matters in any calculation involving averages or prices, where truncating instead of rounding can produce noticeably wrong results.