Variables

💡 Big Idea

A variable is a named container that holds a piece of data. Variables let your program remember things — a score, a name, a temperature — and use or change them later. Without variables, every program would be a dead-end: it could calculate something but never remember the result.

1   What Is a Variable?

Imagine you are doing a maths problem on paper. You write "let x = 5" at the top. Now, every time you see x in the problem, you know what it means. A variable in Python works exactly the same way: you give a name to a value so you can refer to it later.

🔍 Analogy: Labelled Boxes

Picture a row of boxes on a shelf. Each box has a label on it — "score", "player_name", "temperature". You can put something inside a box, look at what's inside, or replace the contents. The label is the variable name; the contents are the variable's value. The key insight: the label stays the same, but the contents can change at any time.

In Python, you create a variable by writing its name, an equals sign, and the value you want to store. This is called an assignment statement.

score = 10
player_name = "Alex"
temperature = 36.6

After these three lines run, Python remembers three things: a number called score, a piece of text called player_name, and a decimal number called temperature. You can now use those names anywhere in your program.

2   The Vocabulary of Variables

Before going further, let's nail down the key terms you will use — and hear — constantly when talking about variables.

TermWhat It MeansExample
VariableA named container that stores a value in memory.age
ValueThe actual data stored inside the variable.15
AssignmentThe act of storing a value into a variable using =.age = 15
Assignment operatorThe = symbol. It does not mean "equals" — it means "store this value into this name".=
Data typeThe kind of data a variable holds — a whole number, text, a decimal, etc.int, str, float
Re-assignmentStoring a new value into a variable that already exists, replacing the old one.age = 16
ExpressionA piece of code that produces a value — could be maths, text, or a function call.age + 1
StatementA complete instruction that Python carries out. An assignment is a type of statement.age = age + 1
⚠️ Common Confusion: = vs ==

In Python (and most programming languages), = means assignment — "put this value in this box". It does not mean "these two things are equal". The double equals == is used to check whether two things are equal. Mixing these up is one of the most common beginner errors. You will make this mistake. So will everyone else. Now you know to look for it.

3   Data Types

Not all values are the same kind of thing. The number 42 is different from the text "42". Python needs to know what kind of value is stored in a variable so it knows what operations make sense. This is called the variable's data type.

Here are the four core data types you will use constantly in Grade 9:

Type NameShort name in PythonWhat it storesExamples
IntegerintWhole numbers, positive or negative. No decimal point.0, 42, -7, 1000
FloatfloatNumbers with a decimal point.3.14, -0.5, 99.9
StringstrText — any sequence of characters, wrapped in quotes."hello", "42", "!!"
BooleanboolA true/false value. Only two possible values exist.True, False

3.1   Integers (int)

Integers are whole numbers — no decimal point. They can be positive, negative, or zero. Use them for things you count: a score, a number of players, someone's age.

lives = 3
score = 0
year = 2026
temperature_celsius = -5

3.2   Floats (float)

Floats are numbers with a decimal point. Use them for things you measure: a height, a price, an average. Python automatically decides a number is a float the moment it sees a decimal point.

height_m = 1.75
price = 9.99
average_score = 84.5
🔍 int vs float — which should I use?

A simple rule: if the thing you are storing can never be a fraction (you cannot have 2.5 lives in a game), use int. If it can be a fraction (a price, a measurement, a percentage), use float. When in doubt, think about the real-world thing you are representing.

3.3   Strings (str)

A string is any sequence of characters — letters, numbers, spaces, symbols — wrapped in quote marks. Both single quotes (') and double quotes (") work in Python.

first_name = "Alex"
city = 'Warsaw'
greeting = "Hello, world!"
zip_code = "00-001"   # This is a string, not a number — you'd never do maths with it
⚠️ "42" is not 42

The string "42" and the integer 42 look similar but are completely different. 42 + 1 gives you 43. "42" + 1 gives you an error — you cannot add a number to a piece of text. This is one of the most common beginner mistakes when working with user input, because input() always returns a string, even if the user typed a number.

3.4   Booleans (bool)

A boolean is the simplest data type of all: it can only ever be True or False. Booleans are the foundation of decision-making in code — every if statement ultimately checks whether something is True or False.

game_over = False
is_logged_in = True
has_won = False

Notice that True and False are capitalised in Python. true (lowercase) will cause an error — Python is case-sensitive.

✅ Check Your Understanding
  1. What data type would you use to store a student's exam score out of 100? What about their name? What about whether they passed?
  2. Look at this code: x = "7". What type is x? What would happen if you tried to do x + 3?
  3. What is the difference between = and ==? Write one sentence for each.
  4. Predict the data type of each of these values: 3.0   3   "3"   True   "False"
  5. A student writes age = 15.0. It works — but is it the best choice? Why or why not?

4   Naming Your Variables

You have a lot of freedom in naming variables, but there are rules and conventions you must know. Breaking the rules causes errors. Ignoring the conventions makes your code hard for others (and future-you) to read.

4.1   The Rules (Python enforces these)

RuleValid ExampleInvalid Example
Names can only contain letters, digits, and underscores ( _ ).player_1player-1   (hyphen not allowed)
Names cannot start with a digit.score11score
Names are case-sensitive. Score and score are two different variables.score, ScoreUsing them interchangeably by accident.
Reserved words (keywords) cannot be used as variable names.my_listlist, if, for, True

4.2   The Conventions (the Python community expects these)

Conventions are not enforced by Python — your code will run either way. But good programmers follow them because they make code easier to read for everyone.

ConventionGoodAvoid
Use snake_case: lowercase words separated by underscores.player_name, high_scoreplayerName, PlayerName
Use descriptive names — say what the variable holds.student_age, total_pricex, a, thing
Avoid single letters (except in short loops or maths formulas).width, heightw, h
Keep names short but not cryptic.avg_scoreaverage_score_of_all_students_in_class
🔍 Why Names Matter

Imagine reading a program where every variable is called a, b, or x. You would have to trace through the entire program to figure out what each one holds. Good variable names make code self-documenting — the name tells you the purpose without needing a comment. Professional programmers spend real time choosing names, and code reviews often raise naming as a discussion point.

5   Assignment and Re-assignment

When you first store a value in a variable, that is called assignment. When you store a new value into a variable that already has one, that is called re-assignment. The old value is gone — overwritten.

score = 0          # Assignment: score is created and set to 0
print(score)       # Output: 0

score = 10         # Re-assignment: the old value (0) is replaced by 10
print(score)       # Output: 10

score = score + 5  # Re-assignment using the old value to calculate the new one
print(score)       # Output: 15

That last line is worth pausing on: score = score + 5. In maths class, this would be nonsense. But in Python, the right side is always evaluated first. Python reads it as: "take the current value of score (10), add 5 to it (giving 15), then store 15 back into score."

🔍 Analogy: A Scoreboard

Think of a scoreboard at a sports game. The board shows a number. When a team scores, the operator does not create a new board — they update the existing number. score = score + 1 is the programming equivalent of "add 1 point to whatever the score currently shows."

5.1   Shorthand Assignment Operators

Because updating a variable using its own value is so common, Python gives you shorthand operators:

ShorthandEquivalent toMeaning
score += 5score = score + 5Add 5 to score.
score -= 3score = score - 3Subtract 3 from score.
score *= 2score = score * 2Multiply score by 2.
score //= 2score = score // 2Integer-divide score by 2.

You will see += constantly — in loops, games, counters, and totals. Get comfortable with it early.

✅ Check Your Understanding
  1. What is the output of this program? Trace it line by line before running it.

    x = 5
    x = x * 2
    x += 3
    print(x)
  2. Which of these variable names are invalid in Python? For each invalid name, explain why.

    my_score    2nd_place    player-hp    total$    for    _temp
  3. A student writes count = count + 1 but gets an error: "name 'count' is not defined". What did they forget to do before this line?
  4. Rewrite these using shorthand operators:

    lives = lives - 1
    price = price * 1.2
    total = total + item_cost
  5. True or False: after x = 10 and then x = 20, Python remembers both values. Explain your answer.

6   Checking and Converting Types

Python gives you two useful built-in tools for working with types: one to check what type a variable is, and a set of functions to convert between types.

6.1   Checking a Type with type()

The type() function tells you exactly what data type a variable holds. This is particularly useful when debugging.

age = 15
name = "Alex"
height = 1.75
is_enrolled = True

print(type(age))          # <class 'int'>
print(type(name))         # <class 'str'>
print(type(height))       # <class 'float'>
print(type(is_enrolled))  # <class 'bool'>

6.2   Converting Between Types

Sometimes you need to convert a value from one type to another. This is called type conversion (or casting). Python provides built-in functions for the most common conversions:

FunctionConverts toExampleResult
int()Integerint("42")42
float()Floatfloat("3.14")3.14
str()Stringstr(100)"100"
bool()Booleanbool(0)False

The most common place you will need type conversion is when working with user input. The input() function always returns a string, even if the user types a number. Forgetting this causes one of the most frequent beginner errors:

age = input("How old are you? ")   # User types 15 — but age is the STRING "15"
next_year = age + 1                 # ERROR: cannot add a string and an integer

# The fix: convert first
age = int(input("How old are you? "))
next_year = age + 1                 # Now this works: 15 + 1 = 16
print("Next year you will be", next_year)
✅ Check Your Understanding
  1. What does type(3.0) return? What about type(3)? Are they the same?
  2. A program asks the user to enter two numbers and prints their sum. A student writes:

    a = input("First number: ")
    b = input("Second number: ")
    print(a + b)

    The user enters 4 and 5. The program prints 45 instead of 9. Why? How do you fix it?

  3. What happens if you try to do int("hello")? Make a prediction, then try it — what error do you get?
  4. Convert this value so the maths works correctly, then predict the output:

    price = "19"
    tax_rate = 0.2
    total = price * (1 + tax_rate)
    print(total)

7   Putting It Together: Variables in a Real Program

Here is a short but complete program that uses everything covered in this article. Read it carefully and try to predict the output before scrolling down.

player_name = input("Enter your name: ")
score = 0
lives = 3

print("Welcome,", player_name)
print("Score:", score, "| Lives:", lives)

score += 50
lives -= 1

print("--- After round 1 ---")
print("Score:", score, "| Lives:", lives)

final_message = player_name + " finished with a score of " + str(score)
print(final_message)

Notice a few things:

  • score and lives are updated using += and -=.
  • To combine player_name (a string) with score (an integer) in one line of text, we must convert score to a string first using str(score).
  • Every variable has a clear, descriptive name — you can read the program almost like a sentence.

8   Final Check: The Big Picture

💡 Big Idea

Variables are named containers that store values. Every variable has a name, a value, and a data type. You assign values with =, update them with operators like +=, and convert between types when needed. Choosing clear, descriptive names is not optional — it is part of writing good code.

✅ Final Check Your Understanding
  1. In your own words: what are the three things every variable has?
  2. Trace this program step by step. Write the value of x after each line.

    x = 100
    x -= 25
    x *= 2
    x += 10
    print(x)
  3. Write a short program (4–6 lines) that:
    • Asks the user for their age.
    • Stores it as an integer.
    • Calculates what year they were born (use 2026 as the current year).
    • Prints a message like: "You were born in 2011."
  4. A classmate shows you this code:

    a = 5
    b = 3
    a = b
    b = a
    print(a, b)

    They expect the output to be 3 5 (swapped). What does it actually print, and why? How would you fix it?

  5. Explain in plain English why this line of code works even though it looks like a maths error: count = count + 1

9   Quick-Reference Glossary

TermOne-line definition
variableA named storage location that holds a value.
assignment ( = )Storing a value into a variable for the first time.
re-assignmentReplacing the value in a variable that already exists.
data typeThe kind of data a variable holds: int, float, str, or bool.
intA whole number with no decimal point.
floatA number with a decimal point.
strA sequence of characters (text), wrapped in quote marks.
boolA true/false value: either True or False.
type()A built-in function that tells you the data type of a value.
type conversion (casting)Converting a value from one type to another using int(), float(), str(), etc.
snake_caseThe Python naming convention: lowercase words joined by underscores.
expressionA piece of code that produces a value, such as x + 5.
statementA complete instruction that Python carries out, such as x = 10.