Beginner

Variables in Python

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!

Definition

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.

What Does "Named Reference" Mean?

When you create a variable, you're doing two things:

  1. Storing a value in your computer's memory (RAM)
  2. Creating a label (the variable name) that points to that memory location

Think of it like this:

Instead of remembering cryptic memory addresses, you just use the name age, and Python handles the rest!

What is "Stored in Memory"?

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.

Python's Dynamic Typing

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!

Analogy

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.

Visual (Mental Model)

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

Examples

Example 1: Basic Variable Creation (Simple)

# 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:

Example 2: Variables Can Change (Intermediate)

# 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."

Example 3: Checking Variable Types (Intermediate)

# 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)

Example 4: Practical Use Case (Practical)

# 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!

Hands-On: Create Your Personal Info Variables

Let's practice creating variables and using them in sentences.

Step 1: Create a New File

  1. Open your python-projects folder (or create it if you haven't)
  2. Create a new file called my_info.py
  3. Open it in your text editor (VS Code, Notepad, etc.)

Step 2: Create Variables for Personal Information

# 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.")

Step 3: Run Your Program

python my_info.py

Step 4: Expected Output

Hello! My name is Aisha Kumar
I was born in 2004
I am approximately 21 years old.

Common Mistakes

Mistake 1: Using Spaces in Variable Names

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.

Mistake 2: Case Sensitivity

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!

Mistake 3: Using Reserved Keywords

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

Mini-Project: Interactive Greeting Program

Goal: Create a program that asks for the user's information and provides a personalized greeting with calculations.

Project Requirements:

Complete Implementation

# 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)

Summary

Key Takeaways:

Variable Naming Best Practices:

✅ DO:

❌ DON'T:

💡 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! 🐍

🎯 Test Your Knowledge: Variables in Python

Answer these questions to check your understanding of Python variables

1. Which of the following is a valid variable name in Python?

2cool_name
user_name
user-name
class

2. What will happen when you run this code: x = 5 then x = "hello"?

Python will throw an error
x will now store the string "hello"
x will store both 5 and "hello"
The first assignment will be ignored

3. What naming convention is recommended for Python variables?

camelCase (e.g., userName)
snake_case (e.g., user_name)
PascalCase (e.g., UserName)
kebab-case (e.g., user-name)

4. In Python, do you need to declare the type of a variable before using it?

Yes, always
No, Python is dynamically typed
Only for numbers
Only for strings
← Previous: About Python Next: Data Types →