Skip to main content

📦 Lesson 3: Variables — Teaching Python to Remember

Imagine you have a bunch of labeled boxes where you can store things. That's exactly what variables are in programming — labeled containers for storing information!

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Create variables to store different types of data
  • Follow Python's variable naming rules and conventions
  • Work with integers, floats, strings, and booleans
  • Use f-strings to embed variables in text output
  • Check variable types with type() and avoid common mistakes

Estimated Time: 45–60 minutes

Project: Build a shopping calculator that uses variables and f-strings to print a receipt

In This Lesson

📦 What Are Variables?

Imagine you have a bunch of labeled boxes where you can store things. That's exactly what variables are in programming — labeled containers for storing information!

🏷️ Variables are like labeled boxes name "Alice" 📝 String (text) age 25 🔢 Integer (whole number) height 5.7 🔢 Float (decimal) The label is the variable name — the contents are the value
Figure 1: Variables store data in labeled containers — each has a name and a value.

📖 Real-World Analogy

Think of variables like contact entries in your phone: the contact name is like the variable name, the phone number is like the value stored, you can update a contact's number (the variable's value changes), and you can have different types of info — phone, email, address — just like different data types.

✏️ Creating Variables

Creating a variable is as simple as giving a name to a value:

# Creating variables
my_name = "Sarah"
my_age = 28
my_height = 5.6
likes_pizza = True

# Using variables
print("Hello, my name is", my_name)
print("I am", my_age, "years old")
print("I am", my_height, "feet tall")
print("I like pizza:", likes_pizza)

Output:

Hello, my name is Sarah
I am 28 years old
I am 5.6 feet tall
I like pizza: True

✅ Pro Tip

Choose variable names that explain what they store. Future you (and other programmers) will thank you! Instead of x = 25, use age = 25. Your code tells a story — make it a clear one!

📏 Variable Naming Rules

Just like you can't name your pet "123" or "my-dog", Python has rules for naming variables:

graph TD A["🏷️ Variable Names"] --> B["✅ Must Start With"] A --> C["✅ Can Contain"] A --> D["❌ Cannot Be"] B --> E["Letter or _"] C --> F["Letters, Numbers, _"] D --> G["🚫 Python Keywords"] D --> H["🚫 Start with Number"] D --> I["🚫 Contain Spaces"]

Good Variable Names vs Bad Variable Names

# Good names - descriptive and follow rules
user_name = "John"
age_in_years = 30
total_score = 95.5
is_student = True

# Bad names - these will cause errors!
# 2fast = "car"         # Can't start with number
# my-name = "Bob"       # No hyphens allowed
# my age = 25           # No spaces allowed
# class = "Math"        # 'class' is a Python keyword
✅ Good Name ❌ Bad Name Why It's Bad
user_name2fastCan't start with a number
age_in_yearsmy-nameHyphens not allowed
total_scoremy ageSpaces not allowed
is_studentclassReserved Python keyword

📌 Constants in Python

While Python doesn't have true constants, we use UPPERCASE names to indicate values that shouldn't change:

# Constants - values that shouldn't change
PI = 3.14159
MAX_USERS = 100
DEFAULT_COLOR = "blue"
TAX_RATE = 0.08

# Use them like regular variables
circle_area = PI * radius ** 2
final_price = price * (1 + TAX_RATE)

Convention: UPPERCASE_WITH_UNDERSCORES for constant names.

🗂️ Types of Data

Python variables can store different types of information, like different sections in your backpack:

🐍 Python Data Types 🔢 Integer (int) 42, -7, 0, 1000 Whole numbers — no decimals 🔢 Float 3.14, -0.5, 99.9 Decimal numbers 📝 String (str) "Hello", 'Python' Text in quotes ✅ Boolean (bool) True / False Yes/No values
Figure 2: The four core Python data types you'll use most often.

🔍 Checking Variable Types

Use the type() function to see what kind of data a variable holds:

# Check the type of any variable
age = 25
print(type(age))          # <class 'int'>

height = 5.9
print(type(height))       # <class 'float'>

name = "Python"
print(type(name))         # <class 'str'>

is_student = True
print(type(is_student))   # <class 'bool'>

# Useful for debugging!
mystery = "42"
print(f"mystery contains {mystery} of type {type(mystery)}")

🔄 Variables Can Change!

That's why they're called "variables" — they can vary! Watch this magic:

# Variables can change their values
mood = "happy"
print("I am feeling", mood)

mood = "excited"
print("Now I am feeling", mood)

mood = "sleepy"
print("After coding, I am feeling", mood)

# Variables can even change type!
mystery_box = 42
print("The box contains:", mystery_box)

mystery_box = "a surprise"
print("Now the box contains:", mystery_box)

Output:

I am feeling happy
Now I am feeling excited
After coding, I am feeling sleepy
The box contains: 42
Now the box contains: a surprise
graph LR A["mood = 'happy'"] -->|"reassign"| B["mood = 'excited'"] B -->|"reassign"| C["mood = 'sleepy'"] style A fill:#10b981,color:#fff style B fill:#3b82f6,color:#fff style C fill:#8b5cf6,color:#fff

⚠️ Watch Out

When you assign a new value to a variable, the old value is gone forever. Python doesn't keep a history of previous values unless you save them yourself!

⚙️ Working with Variables

Variables become powerful when you use them together:

# Variables in action
first_name = "Maria"
last_name = "Garcia"
full_name = first_name + " " + last_name
print("Full name:", full_name)

# Math with variables
width = 10
height = 5
area = width * height
print("The area of the rectangle is:", area)

# Updating based on other variables
savings = 100
paycheck = 500
savings = savings + paycheck  # Add paycheck to savings
print("New savings balance:", savings)

Output:

Full name: Maria Garcia
The area of the rectangle is: 50
New savings balance: 600
graph TD A["📝 first_name = 'Maria'"] --> C["🔗 full_name = first_name + ' ' + last_name"] B["📝 last_name = 'Garcia'"] --> C C --> D["🖨️ print → 'Maria Garcia'"]

✨ The Power of F-Strings

Python has a super cool way to include variables in text called f-strings. It's like mail merge for your code!

# Without f-strings (the old way)
name = "Alex"
age = 25
print("Hello, my name is", name, "and I am", age, "years old")

# With f-strings (the modern way)
print(f"Hello, my name is {name} and I am {age} years old")

# F-strings can do math too!
items = 5
price = 10.99
print(f"Total cost for {items} items: ${items * price}")

Output:

Hello, my name is Alex and I am 25 years old
Hello, my name is Alex and I am 25 years old
Total cost for 5 items: $54.95

💎 Advanced F-String Formatting

F-strings can do more than just insert variables:

# Number formatting
price = 19.99
print(f"Price: ${price:.2f}")        # $19.99 (2 decimal places)

percentage = 0.856
print(f"Success rate: {percentage:.1%}")  # 85.6%

large_number = 1234567
print(f"Population: {large_number:,}")    # 1,234,567

# Alignment and padding
name = "Alice"
print(f"|{name:>10}|")   # |     Alice| (right align, 10 chars)
print(f"|{name:<10}|")   # |Alice     | (left align)
print(f"|{name:^10}|")   # |  Alice   | (center)

# Date formatting (with datetime)
from datetime import datetime
today = datetime.now()
print(f"Today is {today:%B %d, %Y}")  # Today is October 15, 2024

🐛 Common Mistakes and How to Fix Them

⚠️ Mistake 1: Using a variable before creating it

# Wrong
print(favorite_color)  # Error! Variable doesn't exist yet
favorite_color = "blue"

# Right
favorite_color = "blue"
print(favorite_color)

✅ Mistake 2: Forgetting quotes around text

# Wrong
name = Sarah  # Error! Python thinks Sarah is a variable

# Right
name = "Sarah"  # Now Python knows it's text

🕵️ Interactive Exercise: Variable Detective

Can you predict what each print statement will show?

# Mystery Code #1
x = 10
y = 3
x = x + y
y = x - y
x = x - y
print(f"x = {x}, y = {y}")  # What will this print?

# Mystery Code #2
word = "Python"
word = word + " is"
word = word + " awesome!"
print(word)  # What will this print?

# Mystery Code #3
temperature = 32
temperature = (temperature - 32) * 5/9
print(f"Temperature in Celsius: {temperature}")  # What will this print?
💡 Reveal Answers

Answers:

# Mystery Code #1 — the values swap!
x = 3, y = 10

# Mystery Code #2 — string concatenation builds up
Python is awesome!

# Mystery Code #3 — Fahrenheit to Celsius
Temperature in Celsius: 0.0

🏋️ Practice Exercises

🏋️ Exercise 1: Personal Information Storage

Objective: Create variables for different data types and display them with f-strings.

Instructions:

Create variables to store:

  1. Your first name
  2. Your favorite number
  3. Your height in inches
  4. Whether you like chocolate (True/False)
  5. Use f-strings to print a sentence using all these variables
💡 Hint

Remember: text goes in quotes, numbers don't, and booleans are True or False (capitalized!).

✅ Solution
first_name = "Alex"
favorite_number = 7
height_inches = 68
likes_chocolate = True

print(f"Hi, I'm {first_name}!")
print(f"My favorite number is {favorite_number}")
print(f"I'm {height_inches} inches tall")
print(f"Do I like chocolate? {likes_chocolate}")

Output:

Hi, I'm Alex!
My favorite number is 7
I'm 68 inches tall
Do I like chocolate? True

🏋️ Exercise 2: Shopping Calculator

Objective: Use variables and math to calculate a shopping total.

Instructions:

  1. Store the price of three items in variables
  2. Calculate the subtotal
  3. Add 8% tax
  4. Print the receipt using f-strings
💡 Hint

Tax is calculated as subtotal * 0.08. Use :.2f in your f-string to show exactly two decimal places for dollar amounts.

✅ Solution
# Shopping Calculator
item1_price = 12.99
item2_price = 24.50
item3_price = 7.99

subtotal = item1_price + item2_price + item3_price
TAX_RATE = 0.08
tax = subtotal * TAX_RATE
total = subtotal + tax

print("=== RECEIPT ===")
print(f"Item 1:   ${item1_price:.2f}")
print(f"Item 2:   ${item2_price:.2f}")
print(f"Item 3:   ${item3_price:.2f}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total:    ${total:.2f}")

Output:

=== RECEIPT ===
Item 1:   $12.99
Item 2:   $24.50
Item 3:   $7.99
Subtotal: $45.48
Tax (8%): $3.64
Total:    $49.12

🏋️ Exercise 3: Temperature Converter

Objective: Use variable math and f-strings to convert temperatures.

Instructions:

  1. Store a temperature in Fahrenheit
  2. Convert it to Celsius using the formula: (F - 32) × 5/9
  3. Store the result in a new variable
  4. Print both temperatures with descriptive text
💡 Hint

Use parentheses to group the subtraction before the multiplication: (fahrenheit - 32) * 5 / 9.

✅ Solution
fahrenheit = 72
celsius = (fahrenheit - 32) * 5 / 9

print(f"{fahrenheit}°F is equal to {celsius:.1f}°C")

Output:

72°F is equal to 22.2°C

🎯 Quick Quiz

Question 1: Which of the following is a valid Python variable name?

Question 2: What does type(3.14) return?

Question 3: What does the following code print?

x = 5
x = x + 3
print(x)

Summary

🎉 Key Takeaways

  • Variables are containers that store information
  • Give variables descriptive names following Python's rules
  • Variables can store different types of data: integers, floats, strings, and booleans
  • Variables can change their values during program execution
  • F-strings (f"...") make it easy to include variables in text
  • Use type() to check what kind of data a variable holds
  • Always create a variable before trying to use it

🚀 What's Next?

Now that Python can remember things with variables, we'll learn how to get input from users. This will make your programs interactive — they'll be able to have conversations with people!

🎉 Congratulations!

You've learned how to teach Python to remember things! Variables are the backbone of every program you'll ever write. Keep experimenting — try storing your own data and see what you can build!