Learn how Python variables store and manage data in memory
Imagine you're building a game. You need to track the player's name, their score, how many lives they have left, and whether they've completed a level. How do you remember all this information while your program runs? That's exactly what variables do—they're your program's memory, storing everything from a single number to complex data. Without variables, your code would be like trying to do math in your head without writing anything down. Let's learn how to give your programs the power to remember!
A variable is a named reference to a value stored in memory. It's a container that holds data you can use, change, and reference throughout your program.
When you create a variable, you're doing two things:
Think of it like this:
0x7fff5fbff6a0 (where the actual data lives)age (the human-friendly label you use)20 (the actual data stored)Instead of remembering cryptic memory addresses, you just use the name age, and Python handles the rest!
Memory (RAM) is your computer's short-term workspace. When you create a variable:
⚠️ Important: Variables only exist while your program is running. They're temporary storage, not permanent files.
Unlike languages like C++ or Java where you must declare types (int age = 20;), Python infers the type automatically:
age = 20 # Python sees 20 and thinks "that's an integer"
name = "Aisha" # Python sees quotes and thinks "that's a string"
price = 19.99 # Python sees a decimal and thinks "that's a float"
You don't tell Python "this is an integer"—Python figures it out. This is called dynamic typing and makes Python beginner-friendly!
A variable is like a labeled jar in your kitchen.
Just like you wouldn't label a jar jar number 3 when you could call it sugar, you give variables meaningful names that describe what they hold.
Memory Representation:
Variable Name Arrow Value Type
───────────── ───── ───────── ──────
price ──────► 19.99 float
name ──────► "Aisha" string (str)
age ──────► 20 integer (int)
is_active ──────► True boolean (bool)
Assignment Flow:
Write Python Store in Memory
↓ ↓ ↓
age = 20 → Interpret: int → RAM: age → 20
# Creating variables - Python assigns types automatically
name = "Aisha" # String (text)
age = 20 # Integer (whole number)
gpa = 3.8 # Float (decimal number)
is_active = True # Boolean (True/False)
# Display all variables
print(name, age, gpa, is_active)
# Output: Aisha 20 3.8 True
What's happening:
= is the assignment operator (stores value on right into variable on left)print() can display multiple values separated by spaces# Variables are called "variable" because they can vary (change)!
score = 0
print("Starting score:", score) # Output: Starting score: 0
score = 10 # Reassign - the old value (0) is replaced
print("After level 1:", score) # Output: After level 1: 10
score = score + 5 # Use the current value to calculate a new one
print("After bonus:", score) # Output: After bonus: 15
# You can even change the type (though usually you don't want to)
score = "Game Over"
print(score) # Output: Game Over
💡 Key insight: The = operator doesn't mean "equals" in math. It means "assign the value on the right to the variable on the left."
# Use type() to see what type Python assigned
name = "Aisha"
age = 20
gpa = 3.8
is_active = True
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
print(type(gpa)) # Output: <class 'float'>
print(type(is_active)) # Output: <class 'bool'>
# Why does this matter? Different types have different capabilities
print(age + 5) # Output: 25 (math works on numbers)
# print(name + 5) # ❌ ERROR: can't add string and number
print(name + "!") # Output: Aisha! (can combine strings)
# E-commerce shopping cart example
# Product information
product_name = "Wireless Mouse"
product_price = 19.99
product_in_stock = True
quantity_available = 47
# Customer order
customer_name = "Alex Chen"
order_quantity = 2
# Calculate total
total_price = product_price * order_quantity
# Display order summary
print("=" * 40)
print("ORDER SUMMARY")
print("=" * 40)
print(f"Customer: {customer_name}")
print(f"Product: {product_name}")
print(f"Price per unit: ${product_price}")
print(f"Quantity: {order_quantity}")
print(f"Total: ${total_price}")
print(f"In stock: {product_in_stock}")
print("=" * 40)
💡 Notice: We use descriptive names like product_price instead of just p or x. This makes code readable!
Let's practice creating variables and using them in sentences.
python-projects folder (or create it if you haven't)my_info.py# my_info.py - Store and display personal information
# Create variables with your information
first_name = "Aisha" # Replace with your first name
last_name = "Kumar" # Replace with your last name
year_of_birth = 2004 # Replace with your birth year
current_year = 2025
# Calculate age (approximately)
age = current_year - year_of_birth
# Create a friendly sentence using your variables
print("Hello! My name is", first_name, last_name)
print("I was born in", year_of_birth)
print("I am approximately", age, "years old.")
python my_info.py
Hello! My name is Aisha Kumar
I was born in 2004
I am approximately 21 years old.
Problem: Variable names cannot contain spaces.
# ❌ WRONG:
first name = "Aisha"
# SyntaxError: invalid syntax
# ✅ CORRECT:
first_name = "Aisha" # Use underscores (snake_case)
firstName = "Aisha" # Or camelCase (less common in Python)
⚠️ Prevention tip: Always use snake_case for variable names in Python: user_score, total_price, is_active.
Problem: Python treats Name, name, and NAME as three different variables.
name = "Aisha"
Name = "Bob"
NAME = "Charlie"
print(name) # Output: Aisha
print(Name) # Output: Bob
print(NAME) # Output: Charlie
# These are three separate variables!
Problem: You can't name variables after Python's built-in words.
# ❌ WRONG - These are Python keywords:
for = 10 # SyntaxError
if = 20 # SyntaxError
class = 30 # SyntaxError
print = 40 # ⚠️ This "works" but breaks print()!
# ✅ CORRECT - Add extra context:
for_loop_count = 10
if_condition = 20
class_name = 30
print_count = 40
Goal: Create a program that asks for the user's information and provides a personalized greeting with calculations.
# greeting.py - Interactive user greeting
# Get user information
user_name = input("What is your name? ")
birth_year = input("What year were you born? ")
# Convert birth_year to integer (input() gives us text)
birth_year = int(birth_year)
# Calculate age
current_year = 2025
age = current_year - birth_year
# Get more info
favorite_hobby = input("What is your favorite hobby? ")
# Display personalized greeting
print("\n" + "=" * 50)
print("✨ PERSONALIZED GREETING ✨")
print("=" * 50)
print(f"Hello, {user_name}! 👋")
print(f"You were born in {birth_year}.")
print(f"That makes you approximately {age} years old!")
print(f"It's awesome that you enjoy {favorite_hobby}! 🎉")
print("=" * 50)
user_score or product_pricelowercase_with_underscores, not camelCase or PascalCase= operator assigns, not equals — Think "store the value on the right into the variable on the left"✅ DO:
user_score not ussnake_case: first_name not firstNameusers, scores❌ DON'T:
i, j)for, class, if1st_placeuser@name, total$x, temp, data (unless context is clear)💡 Remember: Variables are the building blocks of programming. Every program you write will use them. The better you name them, the easier your code is to read and maintain. Don't rush—take time to choose good names! 🐍
Answer these questions to check your understanding of Python variables
1. Which of the following is a valid variable name in Python?
2. What will happen when you run this code: x = 5 then x = "hello"?
3. What naming convention is recommended for Python variables?
4. In Python, do you need to declare the type of a variable before using it?