Why Does This Matter?
Imagine you are filling out a form online — your name goes in one box, your age in another, your email in a third. Each box has a label and stores a piece of information. Variables in Python work exactly the same way. They are labelled containers that hold data so your program can remember things and use them later.
Without variables, a program would forget everything the moment it moved to the next line. You could not keep track of a player's score, remember someone's name, or calculate a total. Variables are the building blocks of every program you will ever write.
Think about a game you play on your phone. It remembers your high score, your username, and your level. All of that information is stored in variables behind the scenes. Every app on your phone — from Instagram to your calculator — relies on variables to function. Today, you will learn how to create your own.
Variables in the Real World
Variables are not just an abstract programming concept. They are everywhere in the software you use every single day:
- Game development: Every game stores information like
health = 100,score = 0,level = 1, andplayer_name = "Alex". When you collect a power-up, the game updates a variable. When you take damage, another variable changes. The entire game state is just a collection of variables working together. - Social media: Your profile on any platform is a set of variables —
username = "coder_99",followers_count = 342,is_verified = False,bio = "Year 10 student". Every like, follow, and post updates variables in a database somewhere. - Weather apps: When you check the weather, the app displays variables like
temperature = 18.5,humidity = 72,wind_speed = 15.3, andis_raining = True. These values are updated constantly from weather stations around the world. - Banking: Your bank account is essentially a variable called
account_balance. Every time you receive money, it goes up. Every time you buy something, it goes down. The bank's software updates this variable with every single transaction.
By the end of this chapter, you will be able to:
- Create variables to store different pieces of information
- Understand the four main data types: strings, integers, floats, and booleans
- Use the
type()function to check what kind of data a variable holds - Change the value stored in a variable
- Convert between different data types
- Use augmented assignment operators like
+=and-= - Follow Python naming conventions including constants
- Assign multiple variables in a single line
See It in Action
Example 1: Creating Variables
Creating a variable in Python is beautifully simple. You pick a name, use the = sign, and then write the value you want to store. Python figures out the rest. Let's create some variables and print them out.
15
Computer Science
# Creating variables is as easy as picking a name and giving it a value
name = "Alice"
age = 15
favourite_subject = "Computer Science"
# Now let's use them
print(name)
print(age)
print(favourite_subject)
name to my_name? Does it still work?
Example 2: Data Types
Not all data is the same. A name is text, an age is a whole number, a price might have decimal places, and a yes/no question is either true or false. Python has a different data type for each of these. We can use the type() function to find out what type a variable is.
type() will Python report? Will 42 and 18.5 have the same type? Think carefully, then run to find out.
42 is type: <class 'int'>
18.5 is type: <class 'float'>
False is type: <class 'bool'>
# str - a string (text)
greeting = "Hello, World!"
print(greeting, "is type:", type(greeting))
# int - an integer (whole number)
score = 42
print(score, "is type:", type(score))
# float - a floating-point number (decimal)
temperature = 18.5
print(temperature, "is type:", type(temperature))
# bool - a boolean (True or False)
is_raining = False
print(is_raining, "is type:", type(is_raining))
pi and set it to 3.14159. Print its type. Then try is_student = True and check its type. Notice that True and False must start with a capital letter in Python.
Example 3: Changing Variables
Variables are called "variables" because their values can vary — they can change! This is incredibly useful. Think about a game: your score starts at zero and goes up every time you collect a coin. Let's see how that works.
score variable several times. Trace through it line by line: what will the final value of score be after the bonus star? And what name will be printed at the end?
After first coin: 10
After second coin: 20
After bonus star: 70
Player: Guest
Player: SuperCoder99
# Starting score
score = 0
print("Starting score:", score)
# Player collects a coin worth 10 points
score = score + 10
print("After first coin:", score)
# Player collects another coin
score = score + 10
print("After second coin:", score)
# Player finds a bonus star worth 50 points
score = score + 50
print("After bonus star:", score)
# Player's name can change too
player = "Guest"
print("Player:", player)
player = "SuperCoder99"
print("Player:", player)
score = score * 2 to double the score?
Example 4: Augmented Assignment Operators
Writing score = score + 10 works perfectly, but Python gives you a shortcut. Instead of repeating the variable name, you can use augmented assignment operators like +=, -=, and *=. These do exactly the same thing but with less typing — and programmers love less typing!
# Start with a score of 100
score = 100
print("Starting score:", score)
# Add 25 points (same as score = score + 25)
score += 25
print("After bonus (+25):", score)
# Lose 10 points (same as score = score - 10)
score -= 10
print("After penalty (-10):", score)
# Double the score (same as score = score * 2)
score *= 2
print("Score doubled (*2):", score)
# These work with floats too
price = 19.99
price -= 5.00
print("Discounted price:", price)
lives set to 3. Use -= to remove a life, then print the result. What happens if you keep removing lives until the number goes below zero? Can you use += to add an extra life?
Example 5: Constants and Naming Conventions
Sometimes you have values in your program that should never change — like the value of pi, the maximum score in a game, or the number of lives a player starts with. In Python, we call these constants. We write their names in ALL_UPPER_CASE to signal to other programmers: "Do not change this value!"
# Constants - values that should not change
# Written in UPPER_CASE by convention
PI = 3.14159
MAX_SCORE = 100
STARTING_LIVES = 3
GAME_TITLE = "Space Invaders"
# Regular variables - values that DO change
# Written in lower_snake_case
current_score = 0
lives_remaining = STARTING_LIVES
player_name = "Aisha"
# Using constants in calculations
radius = 5
area = PI * radius * radius
print(GAME_TITLE)
print("Player:", player_name)
print("Lives:", lives_remaining)
print("Max possible score:", MAX_SCORE)
print("Circle area with radius", radius, "is", area)
GRAVITY = 9.8 and use it to calculate how far an object falls in 3 seconds using the formula distance = 0.5 * GRAVITY * time * time. Print the result.
Example 6: Multiple Assignment
Python lets you assign values to several variables in a single line. This is not just a neat trick — it is genuinely useful, especially when you want to set up several related variables at once or swap the values of two variables.
# Assign multiple variables in one line
x, y, z = 1, 2, 3
print("x =", x)
print("y =", y)
print("z =", z)
# This is great for setting up related data
name, age, city = "Priya", 15, "Manchester"
print(name, "is", age, "and lives in", city)
# Swapping two variables - the Python way!
a = "hello"
b = "world"
print("Before swap: a =", a, ", b =", b)
# In most languages, you'd need a temporary variable
# In Python, you can just do this:
a, b = b, a
print("After swap: a =", a, ", b =", b)
# You can also assign the same value to multiple variables
red = green = blue = 0
print("RGB:", red, green, blue)
gold, silver, bronze in a single line and assign them the values 1st, 2nd, 3rd (as strings). Print them all. Then try swapping gold and bronze — can you do it in one line?
How Does It Work?
Variable Naming Rules
You cannot call a variable just anything. Python has some rules about what makes a valid variable name:
- Must start with a letter or an underscore (
_) — never a number - Can contain letters, numbers, and underscores — but no spaces or special characters
- Case-sensitive —
Name,name, andNAMEare three completely different variables - Cannot use Python keywords — words like
print,if,for, andTrueare reserved
The recommended style in Python is called snake_case — all lowercase letters, with words separated by underscores. For example: player_name, high_score, is_game_over. This makes your code easy to read, and it is what professional Python developers use every day.
firstName, totalScore, numberOfPlayers. In your exams, pseudocode may use either convention. In Python, always use snake_case.
# Good variable names
player_name = "Aisha"
score_2 = 100
_secret = "hidden"
favouriteColour = "blue"
print(player_name, score_2, _secret, favouriteColour)
# These would cause errors (uncomment to test):
# 2nd_place = "Bob" # starts with a number
# my name = "Charlie" # contains a space
# for = "David" # 'for' is a Python keyword
age = 15 is much clearer than x = 15. Good names make your code easier to read — both for others and for your future self. Imagine coming back to your code in six months: would you know what x means? Probably not. But student_age? That is crystal clear.
The Four Main Data Types
Python has many data types, but at this stage you need to know four:
| Type | Name | What It Stores | Examples |
|---|---|---|---|
str |
String | Text — letters, words, sentences | "Hello", 'Python', "42" |
int |
Integer | Whole numbers (positive or negative) | 15, -3, 0, 1000 |
float |
Float | Decimal numbers | 3.14, -0.5, 100.0 |
bool |
Boolean | True or False (only two possible values) | True, False |
Notice that "42" (with quotes) is a string, but 42 (without quotes) is an integer. The quotes make all the difference! A string is just text — Python does not treat it as a number, even if it looks like one.
int age = 15; or String name = "Alice";, explicitly telling the computer what type each variable is. Python's approach is simpler, but it means you need to be more careful about keeping track of your types yourself!
is_raining = True, you are using ideas that are over 150 years old!
Type Conversion (Casting)
Sometimes you need to change a value from one type to another. This is called type conversion or casting. For example, if a user types in their age, it arrives as text (a string), but you might need it as a number to do maths with it. Python gives you functions to convert between types:
# Converting between types
age_text = "15" # This is a string
age_number = int("15") # Convert string to integer
print(age_number + 1) # Now we can do maths: prints 16
# Convert integer to string
score = 100
message = "Your score is " + str(score)
print(message)
# Convert to float
whole_number = 7
decimal_number = float(whole_number)
print(decimal_number) # Prints 7.0
# Convert to boolean
print(bool(1)) # True (any non-zero number is True)
print(bool(0)) # False (zero is False)
print(bool("hello")) # True (any non-empty string is True)
print(bool("")) # False (empty string is False)
# Check the types
print(type(age_text))
print(type(age_number))
print(type(decimal_number))
The Assignment Operator
In maths, = means "is equal to". In Python, = means something different: it means "assign the value on the right to the variable on the left". This is why score = score + 10 makes sense in Python even though it looks impossible in maths. It means "take the current value of score, add 10, and store the result back in score".
= sign in Python is the assignment operator. It does not mean "equals" — it means "store this value". Think of it as an arrow pointing left: name ← "Alice".
Arithmetic Operators
When writing programs, you need to perform calculations. Here are the arithmetic operators you must know for Python and your exams:
| Operator | Name | What It Does | Example | Result |
|---|---|---|---|---|
| + | Addition | Adds two numbers together | 5 + 3 |
8 |
| - | Subtraction | Takes one number away from another | 10 - 4 |
6 |
| * | Multiplication | Multiplies two numbers | 4 * 3 |
12 |
| / | Division | Divides one number by another (includes decimals) | 7 / 2 |
3.5 |
| // | Integer Division | Divides and gives whole number only (no decimals) | 7 // 2 |
3 |
| % | Modulus (Remainder) | Gives the remainder after division | 7 % 2 |
1 |
| ** | Exponent (Power) | Raises a number to a power | 2 ** 3 |
8 (2×2×2) |
DIV for integer division, MOD for modulus, and ^ for exponent. In Python, these are //, %, and ** respectively. Make sure you know both!
Integer Division (//) and Modulus (%) — The Tricky Ones
These two operators confuse many students, but they are simple once you understand them.
Imagine sharing 17 sweets between 5 friends equally. Each friend gets 3 sweets (the whole number part).
17 // 5 = 3
Integer division ignores the remainder and only gives you the whole number.
After sharing 17 sweets between 5 friends, there are 2 sweets left over (the remainder).
17 % 5 = 2
Modulus tells you what is left over after dividing as many times as you can.
# Integer division (//) - gives the whole number only
print("17 // 5 =", 17 // 5) # 3 (each friend gets 3 sweets)
# Modulus (%) - gives the remainder
print("17 % 5 =", 17 % 5) # 2 (2 sweets left over)
# Exponent (**) - raises to a power
print("2 ** 3 =", 2 ** 3) # 8 (2 x 2 x 2)
# Is a number even or odd? Use % 2
number = 7
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
# Get the last digit of a number
big_number = 1234
last_digit = big_number % 10
print("Last digit of", big_number, "is", last_digit)
number % 2. If the result is 0, it’s even. If the result is 1, it’s odd. Other common uses: get the last digit (1234 % 10 = 4) and wrap-around values (clock times, game levels).
Common Mistakes
Even experienced programmers make mistakes with variables. Here are the most common ones — learn to recognise them now, and you will save yourself hours of debugging later!
Writing
my name = "Ali" will cause a SyntaxError. Variable names cannot contain spaces. Use an underscore instead: my_name = "Ali".
Writing
1st_place = "Winner" will cause a SyntaxError. Variable names must start with a letter or underscore. Try first_place = "Winner" instead.
Writing
"Age: " + 15 will cause a TypeError because Python cannot join a string and an integer directly. You need to convert the number first: "Age: " + str(15). This is one of the most common errors beginners encounter!
Writing
print = 5 will not cause an immediate error, but it overrides the built-in print() function! After this line, you will no longer be able to print anything. The same goes for input, type, list, and other built-in names. Always choose unique, descriptive names for your variables.
age = "hello" and Python would not complain — it does not know that "age" should be a number. It is up to you to choose sensible names and matching values. Python trusts you!
"5" + "3" gives "53" (joining two pieces of text together), but 5 + 3 gives 8 (adding two numbers). If your program produces unexpected results, check your data types!
# This is a classic gotcha!
# String concatenation vs number addition
print("5" + "3") # Joins text: "53"
print(5 + 3) # Adds numbers: 8
# This is why type() is your friend
x = "hello"
print(x, "is a", type(x))
x = 42
print(x, "is a", type(x))
# Common mistake: forgetting str()
age = 15
# This would cause an error:
# print("I am " + age + " years old")
# This is the fix:
print("I am " + str(age) + " years old")
final) or JavaScript (const), Python cannot actually stop you from changing a value. The UPPER_CASE naming convention (like MAX_SPEED = 120) is purely a social agreement among Python developers. It is the programmer's way of saying: "I promise not to change this, and neither should you." This philosophy is sometimes described as "we are all consenting adults here."
Worked Example: Building a Character Stats Card
Let's put everything together in a longer example. We will create variables for a game character, display them in a formatted way, and then simulate the character taking damage and levelling up. Follow along step by step.
# === STEP 1: Set up the character's starting stats ===
# We use different data types for different kinds of information
character_name = "Elena the Brave" # str
health = 100 # int
attack_power = 25 # int
is_alive = True # bool
level = 1 # int
experience = 0.0 # float
# A constant for the max health - this should never change
MAX_HEALTH = 100
# === STEP 2: Display the character stats card ===
print("=============================")
print(" CHARACTER STATS CARD")
print("=============================")
print("Name: " + character_name)
print("Level: " + str(level))
print("Health: " + str(health) + "/" + str(MAX_HEALTH))
print("Attack: " + str(attack_power))
print("Alive: " + str(is_alive))
print("XP: " + str(experience))
print("=============================")
# === STEP 3: Simulate taking damage ===
print("\n--- A wild goblin attacks! ---")
damage_taken = 35
health -= damage_taken
print("Ouch! Lost " + str(damage_taken) + " health.")
print("Health is now: " + str(health) + "/" + str(MAX_HEALTH))
# === STEP 4: Simulate levelling up ===
print("\n--- Quest completed! ---")
experience += 50.5
level += 1
attack_power += 5
print("Gained 50.5 XP! Total XP: " + str(experience))
print("LEVEL UP! Now level " + str(level))
print("Attack power increased to " + str(attack_power))
# === STEP 5: Display updated stats ===
print("\n=============================")
print(" UPDATED STATS CARD")
print("=============================")
print("Name: " + character_name)
print("Level: " + str(level))
print("Health: " + str(health) + "/" + str(MAX_HEALTH))
print("Attack: " + str(attack_power))
print("Alive: " + str(is_alive))
print("XP: " + str(experience))
print("=============================")
is_alive to False. Can you add a healing potion that restores 20 health? Make sure health does not go above MAX_HEALTH!
Key Vocabulary
Here are the essential terms you need to know for this topic. You will see these in your exams and in professional programming discussions:
| Term | Definition |
|---|---|
| Variable | A named storage location in memory that holds a value which can change during the program's execution. |
| Data Type | The kind of value a variable holds, which determines what operations can be performed on it. |
| String (str) | A data type that stores text — any sequence of characters enclosed in quotation marks. |
| Integer (int) | A data type that stores whole numbers, both positive and negative (e.g. 42, -7, 0). |
| Float (float) | A data type that stores decimal numbers, also known as floating-point numbers (e.g. 3.14, -0.5). |
| Boolean (bool) | A data type with only two possible values: True or False. Used for yes/no decisions. |
| Assignment Operator | The = symbol, which stores (assigns) the value on the right into the variable on the left. |
| Type Conversion (Casting) | Changing a value from one data type to another using functions like int(), str(), float(). |
| Concatenation | Joining two or more strings together using the + operator (e.g. "Hello" + " " + "World"). |
| Dynamic Typing | A feature of Python where you do not need to declare the type of a variable — Python determines it automatically from the assigned value. |
| Constant | A variable whose value is intended to never change. In Python, written in UPPER_CASE by convention. |
| snake_case | The naming convention used in Python where words are separated by underscores and written in lowercase (e.g. player_name). |
| camelCase | A naming convention where the first word is lowercase and each new word starts with a capital letter (e.g. firstName). Used in JavaScript and pseudocode. |
| Integer Division (//) | Division that returns only the whole number part, discarding any remainder. In pseudocode: DIV. In Python: //. |
| Modulus (%) | An operator that returns the remainder after division. In pseudocode: MOD. In Python: %. |
Your Turn
Create three variables to store your name, your age, and your favourite colour. Then print each one on a separate line. Follow the pseudocode below — just replace the placeholder values with your own information.
my_name and store your name in it (as text)STEP 2: Create a variable called
my_age and store your age in it (as a whole number)STEP 3: Create a variable called
my_colour and store your favourite colour in it (as text)STEP 4: Print each variable using
print()
# Exercise 1: All About Me
# Replace the blank values with your own information
my_name = "____"
my_age = ____
my_colour = "____"
print(my_name)
print(my_age)
print(my_colour)
my_name = "Priya" and my_age = 15. Make sure you do not put quotes around your age, or it will be stored as text instead of a number!Create a simple profile card. Store information about a person in variables, then print a neat, formatted introduction. Your output should look something like:
"Hi, my name is Priya. I am 15 years old and I live in Manchester."
STEP 2: Create a variable called
introduction that joins the text and variables together into one sentenceSTEP 3: Print the introduction
STEP 4: Print the type of each variable to check your data types
# Exercise 2: Profile Card
# Create your variables below
name =
age =
city =
# Build your introduction (hint: you'll need str() to convert age)
introduction = "Hi, my name is " + name + ". I am " + str(age) + " years old and I live in " + city + "."
# Print the introduction
print(introduction)
# Print the type of each variable
print(type(name))
print(type(age))
print(type(city))
+, every piece must be a string. Since age is an integer, you need to convert it with str(age) before joining. For example: "I am " + str(15) + " years old". If you see a TypeError, this is almost certainly the issue.Create a program that stores information about your favourite game, film, book, or TV show. Use at least four variables with at least two different data types. Display all the information in a clear, readable way. Be creative with how you present it!
For example, you might store the title, year of release, your rating out of 10, and whether you would recommend it.
STEP 2: Create at least 4 variables using different data types (str, int, float, bool)
STEP 3: Print out the information in a clear, readable format
STEP 4: Use
type() on at least one variable to show the data type
# Exercise 3: My Favourite Thing
# Create your variables and display them below
# Use at least 4 variables and at least 2 different data types
title = "Spider-Man" (string), year = 2021 (integer), rating = 8.5 (float), would_recommend = True (boolean). Then print each one with a label, like print("Title: " + title). Remember to use str() when joining numbers with text!Write a program that stores a temperature in Celsius, converts it to Fahrenheit, and displays both values. The formula to convert Celsius to Fahrenheit is:
F = C × 9/5 + 32
For example, 20°C should convert to 68.0°F.
celsius and store a temperature value (e.g. 20)STEP 2: Create a variable called
fahrenheit and calculate the conversion using the formulaSTEP 3: Print both temperatures with labels, e.g. "20°C is 68.0°F"
STEP 4: Test with different values — try 0, 100, and 37 (body temperature)
# Exercise 4: Temperature Converter
# Store a temperature in Celsius and convert it to Fahrenheit
celsius = ____
# Convert using the formula: F = C * 9/5 + 32
fahrenheit = ____
# Display both temperatures
print(str(celsius) + " degrees C is " + str(fahrenheit) + " degrees F")
# Try changing the celsius value and running again!
# What Fahrenheit value do you get for 0°C? For 100°C?
20. For the formula, write: fahrenheit = celsius * 9/5 + 32. Python follows the standard order of operations (BIDMAS/BODMAS), so the multiplication and division happen before the addition. If you want to be extra safe, you can use brackets: fahrenheit = (celsius * 9 / 5) + 32. Water freezes at 0°C (32°F) and boils at 100°C (212°F) — use these to check your formula is working!Create a "personal stats dashboard" — a program that displays interesting facts and statistics about you in a visually appealing format. Use at least 6 variables of at least 3 different data types.
Think creatively! You could include things like: your name, age, height, number of pets, favourite number, whether you like maths, hours of sleep per night, number of countries visited, and so on. Format the output neatly with borders and labels.
STEP 2: Create at least 6 variables using at least 3 data types (str, int, float, bool)
STEP 3: Display all the information in a formatted, visually appealing way
STEP 4: Include at least one calculation (e.g. your age in days:
age * 365)STEP 5: Use
type() to verify at least two of your variables
# Exercise 5: Personal Stats Dashboard
# Create at least 6 variables of at least 3 different types
# Display them as a formatted dashboard
# Your variables here:
# Your formatted output here:
name = "Your Name" (str)age = 15 (int)height = 1.65 (float, in metres)num_pets = 2 (int)likes_coding = True (bool)sleep_hours = 8.5 (float)For the display, try using
print("=" * 30) to create a border line. You can calculate your approximate age in days with age_in_days = age * 365 and your age in hours with age_in_hours = age_in_days * 24. Remember to use str() when joining numbers with text!
Think About It
- Why do you think Python has different data types instead of treating everything the same? Can you think of a situation where mixing up types could cause a problem?
- If you wrote
age = "fifteen"instead ofage = 15, would Python give an error? Why might this cause issues later in your program? - Why is
score = score + 10not a contradiction? How would you explain what this line does to a friend who has never programmed? - What do you think would happen if you tried to convert the string
"hello"into an integer usingint("hello")? Try it and see! - Why do you think Python uses the convention of UPPER_CASE for constants instead of having a proper constant keyword? What are the advantages and disadvantages of this approach?
- Can you think of a situation where swapping two variables (
a, b = b, a) would be useful in a real program?
Chapter Summary
In this chapter, you have learned the fundamentals of how programs store and manage information. Here is a recap of the key points:
- Variables are named containers that store data in your program's memory. You create them using the assignment operator (
=). - Python has four main data types: strings (
str) for text, integers (int) for whole numbers, floats (float) for decimal numbers, and booleans (bool) for True/False values. - You can check a variable's type using the
type()function and convert between types usingstr(),int(),float(), andbool(). - Augmented assignment operators like
+=,-=, and*=provide shortcuts for updating variable values. - Python is dynamically typed, meaning you do not need to declare a variable's type — Python works it out from the value you assign.
- Constants are written in UPPER_CASE by convention to show their values should not change.
- Good variable names use snake_case, are descriptive, and follow Python's naming rules (no spaces, no starting with numbers, no reserved keywords).
- When joining strings and numbers with
+, you must convert numbers to strings first usingstr().
Exam-Style Questions
Test your understanding with these questions, similar to what you might see in a GCSE Computer Science exam:
Define the term "variable" in programming.
Name the four main data types in Python and give an example of each.
"Hello" (1 mark)Integer (int) — e.g.
42 (1 mark)Float (float) — e.g.
3.14 (1 mark)Boolean (bool) — e.g.
True (1 mark)
Explain why type conversion (casting) is sometimes necessary when writing a Python program. Give an example in your answer.
str(), otherwise Python will produce a TypeError (1 mark). Example: "Age: " + str(15).Extra Resources
Deepen your understanding of variables and data types with these trusted resources:
- BBC Bitesize: Edexcel GCSE Computer Science — Comprehensive revision for programming concepts including variables and data types
- W3Schools: Python Variables — Interactive tutorials and examples for creating and using variables
- W3Schools: Python Data Types — A complete guide to all of Python's built-in data types with try-it-yourself editors
- GCSE Topic 6: Programming Fundamentals — Variables, constants, operators and data types with interactive code editors
- Revision Activities — Memory match and category sort games for programming vocabulary
What's Next?
So far, the information in your programs has been decided by you, the programmer. But what if the user could type their own name? What if they could enter their age, answer a question, or make a choice? In Chapter 3: Input & Output, you will learn how to make your programs truly interactive by getting input from the person running them and displaying beautifully formatted output. Your programs are about to come alive!