Python Variables · The Building Blocks of Programming

Mingming Li — Click any blue heading below to expand the content.

Table of Contents

1. What is a variable?

A variable is like a labeled box that stores information. In Python, you just pick a name, use =, and put something inside.

# Variable examples
name = "Alice"      # a string (text)
age = 25            # an integer (whole number)
height = 1.68       # a float (decimal)
is_student = True   # a boolean (True/False)
Tip: Think of it like this: name = "Alice" means "put the word 'Alice' into a box called 'name'."
Naming rules: Use letters, numbers, and underscores. Cannot start with a number. Use snake_case: player_score, game_active.

2. Common data types

You can check a variable's type with type():

score = 100
print(type(score))   # <class 'int'>
score = "high"
print(type(score))   # <class 'str'>
Dynamic typing: Python is flexible - a variable can change type!
x = 5 (int) -> x = "now text" (str) - Python doesn't mind!

3. Changing and using variables

apples = 10
apples = apples + 5   # apples becomes 15
apples += 3           # shorthand: apples becomes 18

# Combining strings
first = "Hello"
last = "World"
message = first + " " + last   # "Hello World"

# f-strings (Python 3.6+)
name = "Mingming"
print(f"Welcome, {name}!")     # Welcome, Mingming!
Tip: += is a shortcut! apples += 3 is the same as apples = apples + 3.

4. Variable rules & best practices

Warning: Forgetting that score and Score are different! Python is case-sensitive.

5. Quick reference

# Creating variables
name = "value"
number = 42

# Updating
count = count + 1
count += 1          # same as above

# Multiple assignment
a, b = 5, 10        # a=5, b=10

# Swapping values (magic!)
x, y = y, x         # swaps values in one line!

6. Quick Challenge: Spot the Variables

Look at this code from our game (Code-1):

player = pygame.Rect(80, 300, 40, 40)
cactus = pygame.Rect(800, 300, 30, 40)
gravity = 0
game_active = False

Questions:

  1. What are the names of the variables above?
  2. What data type do you think gravity is? (int, float, str, or bool?)
  3. What about game_active?
Click for answers
  1. player, cactus, gravity, game_active
  2. gravity is an int (integer) - it stores whole numbers like 0, 1, 2...
  3. game_active is a bool (boolean) - it stores either True or False

7. Exercises

Try these exercises to practice variables. Write your code in a Python environment (like Thonny).

  • Exercise 1: Create a variable called city and assign it the name of your favorite city. Then create a variable population and assign it a number (in millions). Print both using print().
  • Exercise 2: Create two variables: a = 15 and b = 4. Calculate and store their sum, difference, product, and quotient in new variables. Print each result.
  • Exercise 3: Start with total = 50. Use += to add 25, then -= to subtract 10. What is the final value of total?
  • Exercise 4: Create greeting = "Hello" and name = "Sam". Combine them into message that prints "Hello, Sam!"
  • Exercise 5: Use an f-string to print: "My name is [first] [last] and I am [age] years old."
  • Exercise 6: Swap x = 10 and y = 20 so they become x=20, y=10 (one-line trick!).
  • Exercise 7: Convert temperature = 22.5 (float) to an integer and store in temp_int. Print both.
  • Exercise 8: Predict output before running:
    x = 5
    y = x
    x = 10
    print(y)
  • Exercise 9: Write an if-statement that prints "Bring an umbrella" if is_raining = True.
  • Exercise 10: Ask user for their favorite number using input(), convert to int, print double.

8. Common Errors & Solutions

  • NameError: name 'my_variable' is not defined
    -> You forgot to create the variable before using it! Create it first with =.
  • SyntaxError: invalid syntax
    -> Check for missing quotes, colons, or parentheses.
  • TypeError: can only concatenate str (not int) to str
    -> You tried to add a number to text! Use f-strings or convert with str().
  • Variable name starting with a number
    -> 1st_place is invalid. Use first_place instead.
Debugging tip: Use print() to see what's inside your variables. Add print(gravity) to see its value change!

9. Check Your Understanding

  1. What symbol do we use to assign a value to a variable?
  2. What's the difference between int and float?
  3. How do you check the type of a variable?
  4. What does += do?
  5. What is the shortcut to swap two variables?
Click for Answers
  1. The equals sign =
  2. int = whole numbers, float = numbers with decimals
  3. type(variable_name)
  4. x += 5 is the same as x = x + 5
  5. x, y = y, x

10. Your Progress Tracker

Check off each item as you master it:
I know what a variable is and how to create one
I understand the four main data types (int, float, str, bool)
I can use type() to check variable types
I can update variables using = and +=
I can combine strings with + and f-strings
I know the naming rules for variables
I completed all 10 exercises
I can spot variables in the game code