All 1.2 20 min read 10 question quiz 15 exam marks

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

Python
name = "Aisha"
age = 14
height = 1.62
is_student = True

The 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:

Python
score = 10
score = score + 5     # work out 10 + 5, then make score refer to 15
print(score)          # 15

Naming rules

  • Must start with a letter or underscore
  • May contain letters, digits and underscores, but no spaces
  • Case sensitive, so Score and score are different
  • Cannot be a Python keyword such as if, for or class

Naming well

Python
n = 25                    # bad
num_students = 25         # good
d = 3.5                   # bad
distance_km = 3.5         # good

Python convention is lower_case_with_underscores for variables and UPPER_CASE for constants.

Shortcuts

Python
score += 10     # same as score = score + 10
lives -= 1      # same as lives = lives - 1
total *= 2      # same as total = total * 2
Variables as labelled boxes, with the code that makes themSix lines of code on the left and the boxes they create on the right. The equals sign is assignment: it stores the value on its right in the variable named on its left. Every variable is like a labelled box with a name, a value and a data type. name holds the string Asha, age holds the whole number 15, price holds the decimal 2.5 and passed holds True. The fifth line, age equals age plus one, takes the 15 out and puts 16 in, which shows that the value of a variable can change while its name stays the same. PI is a constant: a value that must never change, written in capitals by convention and shown with a padlock. A card at the bottom left gives the naming rules: use letters, digits and underscores, do not start with a digit and never use a space.variables.py1name = "Asha"2age = 153price = 2.504passed = True5age = age + 16PI = 3.14159Naming a variabletotal_scorewords joined by _age2digits are fine inside2nd_placecannot start with a digitmy scoreno spacesWhat the computer keepsname"Asha"strage16intreplaces 15price2.5floatpassedTrueboolPI3.14159a constant: never changes12345
  1. = stores a value in a variable: the name on the left, the value on the right.
  2. A variable is a labelled box with a name, a value and a data type.
  3. The value can change. age = age + 1 takes the 15 out and puts 16 in.
  4. A constant holds a value that must never change. By convention it is written in capitals.
  5. Names use letters, digits and underscores. No spaces, and no digit first.
The name stays. The value is what you can swap.

Data types

TypeNameExample
Whole numberint42, -7, 0
Decimal numberfloat3.14, -0.5
Textstr"hello", "42"
True or FalseboolTrue, False
NothingNoneTypeNone
Python
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 different

One is a number you can do arithmetic on. The other is text. 42 + 1 gives 43. "42" + "1" gives "421".

Converting between types

Python
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 properly

Choosing 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
The phone number rule

If you would never add or multiply it, store it as a string. Postcodes, ID numbers, phone numbers and card numbers are all strings.

The data types, and changing one into anotherThe five basic data types, one card each. An integer is a whole number such as 42, written int in Python. A real number has a decimal point such as 3.14, written float. A Boolean has only two values, True and False, shown as a switch that is on and a switch that is off. A character is a single symbol such as the letter A, and a string is text inside quote marks. A phone number is stored as a string, because you never do arithmetic on it and because storing it as a number would drop the leading zero, turning 07700 into 7700. Casting changes a value from one type to another: int of the text 42 gives the number 42, str of the number 42 gives the text 42, and int of 3.9 gives 3 because the decimal part is cut off rather than rounded.Integer42-7 0 2025whole numbersintReal3.140.5 -2.75with a decimal pointfloatBooleanTrue Falseonly two valuesboolCharacterAz 7 ?one single symbolstrString"Hi""07700 900123"text in quotesstr1A phone number is a string07700900123you never add phone numbersa number would lose the 007700 as a number = 7700so it is stored as text2Casting: changing type"42"int()42to a whole number42str()"42"to text3.9int()3cuts off the .93
  1. Five data types: integer, real, Boolean, character and string.
  2. A phone number is a string: you never add them, and a number would lose the leading 0.
  3. Casting changes a value from one type to another: int(), str(), float().
Choose the type from what you will do with the value, not from how it looks.
Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

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.

DefineVariable
AnswerA name attached to a value that can change while the program runs.
DefineAssignment
AnswerGiving a variable a value using the equals sign.
Defineint
AnswerThe whole number data type.
Definefloat
AnswerThe decimal number data type.
Definestr
AnswerThe text data type, called a string.
Definebool
AnswerThe data type holding only True or False.
DefineCasting
AnswerConverting a value from one data type to another, such as int() or str().
DefineConstant
AnswerA value that should not change, written in upper case by convention.

Reach the top grade on this topic

  • Choose the correct data type for any piece of data and justify it
  • Explain why 42 + 1 and "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

Avoid these
  • 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.
Fun fact

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

0 of 10 answered
1What does score = score + 5 do if score was 10?
2What type is 3.14?
3What does "5" + "3" give?
4What does int(7.9) give?
5Which type should store whether a user is logged in?
6Why store a phone number as a string?
7What is score += 3 short for?
8Which variable name is invalid in Python?
9What does type("42") return?
10Which is the Python convention for a constant?
Score 0 / 10

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.

15 marks
1State the most suitable data type for each of: a student's age, a product price, whether an order is paid.3 marks
State

Mark scheme0 / 3
  • LAge is an integer
  • LPrice is a float
  • LPaid is a boolean
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain why "10" + "5" gives a different result from 10 + 5.3 marks
Explain

Mark scheme0 / 3
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain why a phone number should be stored as a string rather than an integer.3 marks
Explain

Mark scheme0 / 3
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Write Python code that creates a variable for a player's score starting at zero, adds 25 to it, and prints the result.3 marks
Write

Mark scheme0 / 3
  • LInitialises the variable to 0
  • LAdds 25 to it
  • LPrints the result
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5A program uses int(4.8) and the programmer expects the result 5. Explain what actually happens and how to get the intended result.3 marks
Explain

Mark scheme0 / 3
  • Lint() removes the decimal part rather than rounding
  • LThe result is therefore 4
  • LUse round() to round to the nearest whole number
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 15