📦 Working with Variables
Variables are like containers that store information in your programs. They're one of the most fundamental concepts in programming—imagine labeled boxes where you can put different types of data and use them later.
With variables, your programs become dynamic and useful. You can store user input, remember calculations, and work with different data each time your program runs!
# Creating and using variables
name = "Alice"
age = 25
print(f"Hello, {name}! You are {age} years old.")
📝 Creating Variables (Assignment)
Creating variables in Python is simple! You just give the variable a name and assign it a value using the equals sign (=). This is called the assignment operator—it takes the value on the right and stores it in the variable on the left.
🔤 Basic Variable Assignment
# Creating variables with the assignment operator
name = "John"
age = 30
height = 5.8
is_student = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height} feet")
print(f"Student: {is_student}")
🤖 Python's Automatic Type Detection
One of Python's best features: you don't need to declare what type of data your variable holds! Python automatically determines (detects) the type based on the value you assign.
# Python automatically determines data types
student_name = "Emma" # String (text)
test_score = 95 # Integer (whole number)
grade_average = 87.5 # Float (decimal number)
is_passing = True # Boolean (True/False)
print(f"Student: {student_name}")
print(f"Score: {test_score}")
print(f"Average: {grade_average}")
print(f"Passing: {is_passing}")
🏷️ Variable Naming Rules and Conventions
Python has specific rules for variable names, plus recommended conventions that make your code professional and readable.
⚡ Required Rules (Must Follow)
These rules are enforced by Python—break them and you'll get an error:
# Valid variable names
student_name = "Alice" # Letters and underscores ✓
age2 = 25 # Letters and numbers ✓
_private_var = "hidden" # Can start with underscore ✓
course_2024 = "Python" # Numbers allowed (not at start) ✓
print(f"Student: {student_name}")
print(f"Age: {age2}")
print(f"Course: {course_2024}")
🐍 Naming Convention: snake_case
Python programmers use snake_case for variable names—lowercase letters with underscores between words:
# Good naming convention (snake_case)
user_email = "user@example.com"
total_score = 150
is_logged_in = True
max_attempts = 3
print(f"Email: {user_email}")
print(f"Score: {total_score}")
print(f"Logged in: {is_logged_in}")
print(f"Max attempts: {max_attempts}")
📖 Descriptive Names
Choose names that clearly explain what the variable contains:
# Descriptive names make code self-documenting
monthly_salary = 5000
tax_rate = 0.15
net_income = monthly_salary * (1 - tax_rate)
print(f"Salary: ${monthly_salary}")
print(f"Tax rate: {tax_rate:.1%}")
print(f"Net income: ${net_income}")
🔄 Changing Variable Values (Reassignment)
Variables can be reassigned—you can change their values as your program runs. This is what makes programs dynamic and interactive!
🎯 Basic Reassignment
# Variables can be reassigned anytime
score = 0
print(f"Starting score: {score}")
score = 100
print(f"After first level: {score}")
score = 250
print(f"After bonus round: {score}")
🧮 Using Current Values
You can use a variable's current value to calculate its new value:
# Using current value for new calculation
bank_balance = 1000
print(f"Starting balance: ${bank_balance}")
bank_balance = bank_balance + 500 # Deposit
print(f"After deposit: ${bank_balance}")
bank_balance = bank_balance - 200 # Withdrawal
print(f"After withdrawal: ${bank_balance}")
⚡ Assignment Shortcuts
Python provides handy shortcuts for common math operations:
# Assignment shortcuts save typing
points = 100
print(f"Starting points: {points}")
points += 50 # Same as: points = points + 50
print(f"After bonus: {points}")
points -= 25 # Same as: points = points - 25
print(f"After penalty: {points}")
points *= 2 # Same as: points = points * 2
print(f"After doubler: {points}")
points //= 3 # Same as: points = points // 3 (integer division)
print(f"After division: {points}")
Shortcut | Long Form | Description |
---|---|---|
x += 5 | x = x + 5 | Add 5 to x |
x -= 3 | x = x - 3 | Subtract 3 from x |
x *= 2 | x = x * 2 | Multiply x by 2 |
x //= 4 | x = x // 4 | Integer divide x by 4 |
🗃️ Working with Different Data Types
Variables can store different types of data. Understanding these types helps you choose the right variable for each situation:
📝 Text Data (Strings)
# Working with text (strings)
greeting = "Hello"
name = "Python"
message = greeting + ", " + name + "!"
print(f"Greeting: {greeting}")
print(f"Name: {name}")
print(f"Complete message: {message}")
🔢 Numeric Data
# Working with numbers
whole_number = 42 # Integer
decimal_number = 3.14159 # Float
calculation = whole_number * decimal_number
print(f"Whole number: {whole_number}")
print(f"Decimal: {decimal_number}")
print(f"Result: {calculation:.2f}")
✅ Boolean Data (True/False)
# Working with booleans
is_logged_in = True
has_permission = False
is_admin = True
print(f"Logged in: {is_logged_in}")
print(f"Has permission: {has_permission}")
print(f"Is admin: {is_admin}")
# Boolean logic
can_access = is_logged_in and (has_permission or is_admin)
print(f"Can access system: {can_access}")
🔀 Multiple Assignment
You can assign multiple variables at once:
# Multiple assignment
x, y, z = 10, 20, 30
print(f"Coordinates: x={x}, y={y}, z={z}")
# Swapping variables (Python magic!)
first = "Hello"
second = "World"
print(f"Before swap: {first}, {second}")
first, second = second, first
print(f"After swap: {first}, {second}")
Quick Practice Exercise 💪
Let's practice the basics of working with variables with a few simple tasks!
Hands-on Exercise
Practice creating and using variables with proper naming conventions.
# Variable Practice - Keep it simple!
# Create a variable for your name
my_name = # TODO: Your code here (use quotes for text)
# Create a variable for your age
my_age = # TODO: Your code here (just a number)
# Create a variable for whether you like Python
likes_python = # TODO: Your code here (True or False)
# Practice assignment shortcuts
score = 100
# Add 25 to score using +=
# TODO: Your code here
# Print everything
print(f"Name: {my_name}")
print(f"Age: {my_age}")
print(f"Likes Python: {likes_python}")
print(f"Score: {score}")
Solution and Explanation 💡
Click to see the complete solution
# Variable Practice - Simple solution
# Create a variable for your name
my_name = "Alice"
# Create a variable for your age
my_age = 25
# Create a variable for whether you like Python
likes_python = True
# Practice assignment shortcuts
score = 100
# Add 25 to score using +=
score += 25
# Print everything
print(f"Name: {my_name}")
print(f"Age: {my_age}")
print(f"Likes Python: {likes_python}")
print(f"Score: {score}")
Key Learning Points:
- 📌 Variable Creation: Used
=
to assign values - 📌 Data Types: String, integer, and boolean
- 📌 Assignment Shortcuts: Used
+=
to add to existing value - 📌 F-strings: Displayed variables in formatted text
💪 Variable Best Practices
Follow these practices to write clean, professional code:
1️⃣ Use Descriptive Names
# Good: Clear and descriptive
student_age = 20
monthly_salary = 5000
is_logged_in = True
# Bad: Unclear abbreviations
sa = 20
ms = 5000
li = True
2️⃣ Initialize Variables
Give variables sensible starting values:
# Good practice: Initialize variables
total_score = 0 # Start with zero
player_count = 1 # Start with one player
game_active = False # Start inactive
print(f"Initial state:")
print(f"Score: {total_score}")
print(f"Players: {player_count}")
print(f"Game active: {game_active}")
3️⃣ Use Consistent Naming
Pick a style and stick to it:
# Consistent naming for related data
user_first_name = "John"
user_last_name = "Smith"
user_email = "john.smith@email.com"
user_age = 30
print(f"User: {user_first_name} {user_last_name}")
print(f"Email: {user_email}")
print(f"Age: {user_age}")
📋 Key Variable Concepts Summary
Concept | Example | Important Because |
---|---|---|
Assignment (=) | name = "Alice" | Stores data in variables |
Automatic type detection | Python figures out string vs number | No need to declare types |
Dynamic typing | Variable can change type | Flexibility in programming |
snake_case naming | first_name | Python convention |
Reassignment | score = 100; score = 200 | Variables can change |
Assignment shortcuts | score += 10 | Cleaner math operations |
🧠 Test Your Knowledge
Ready to test your understanding of variables?
🚀 What's Next?
Excellent! You now understand variables—the foundation of all programming. You can create them, name them properly, change their values, and use them to store different types of data.
Variables are just the beginning. Next, we'll dive deeper into the different types of data you can store in variables.
Continue to: Understanding Data Types
Variables are your programming building blocks! 🧱
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.