Variables - Storing Information for Later Use

Think of variables as labeled boxes where you can store information. Once you put something in a box (assign a value), you can use that information anywhere in your program. Variables are one of the most fundamental concepts in programming!

In this lesson, you'll learn:

1. Creating Your First Variables

Creating a variable is simple: you choose a name and assign a value using the equals sign (=).

The pattern is: variable_name = value

The equals sign doesn't mean "equal to" in math - it means "assign this value to this variable."

# Creating variables with different types of information
name = "Alice"
age = 25
height = 5.6
is_student = True

# Using variables in print statements
print("Name:", name)
print("Age:", age)
print("Height:", height, "feet")
print("Is student:", is_student)

Notice how we can store different types of information:

Exercise: Create Personal Information Variables

Create variables to store information about yourself or a fictional character. Include a name, age, and favorite color.

# TODO: Create a variable called name and assign it a string value # TODO: Create a variable called age and assign it a number # TODO: Create a variable called favorite_color and assign it a string # TODO: Print each variable with a descriptive label

2. Rules for Variable Names

Python has specific rules for variable names. Following these rules prevents errors and makes your code easier to read:

# Good variable names
first_name = "John"
last_name = "Smith"
user_age = 28
total_score = 95
is_valid = True

print("Name:", first_name, last_name)
print("Age:", user_age)
print("Score:", total_score)
print("Valid:", is_valid)

Python is case sensitive - these are all different variables:

# Demonstrating case sensitivity
name = "lowercase"
Name = "Capitalized"
NAME = "UPPERCASE"

print("name:", name)
print("Name:", Name)
print("NAME:", NAME)

Always use descriptive names that explain what the variable contains:

# Good practice: descriptive names
student_count = 25
average_temperature = 72.5
book_title = "Python Programming"

print("Students:", student_count)
print("Temperature:", average_temperature)
print("Book:", book_title)

Exercise: Practice Good Variable Names

Create variables with descriptive names for a recipe. Include the recipe name, number of servings, and cooking time in minutes.

# TODO: Create a variable for recipe name (use descriptive variable name) # TODO: Create a variable for number of servings # TODO: Create a variable for cooking time in minutes # TODO: Print all three with appropriate labels

3. Changing Variable Values

Variables are called "variables" because their values can vary (change)! You can assign new values to existing variables at any time. The old value is forgotten and replaced with the new one.

# Starting with an initial value
score = 10
print("Initial score:", score)

# Changing the value
score = 15
print("Updated score:", score)

# Changing to a completely different value
score = 100
print("Final score:", score)

# You can even change the type of data
message = "Hello"
print("Message as text:", message)

message = 42
print("Message as number:", message)

message = True
print("Message as boolean:", message)

Notice that Python doesn't complain when we change the type of data stored in a variable. This flexibility makes Python easy to use, but be careful not to accidentally change types when you don't mean to!

Exercise: Track Changing Values

Create a variable for a player's health in a game. Start with 100, then reduce it to 75, then increase it back to 90, printing the value each time.

# TODO: Create a variable called player_health and set it to 100 # TODO: Print "Starting health:" and the value # TODO: Change player_health to 75 # TODO: Print "After damage:" and the value # TODO: Change player_health to 90 # TODO: Print "After healing:" and the value

4. Using Variables in Calculations

One of the most powerful uses of variables is in calculations. You can use variables anywhere you would use a number, and you can create new variables based on existing ones.

# Basic calculations with variables
length = 10
width = 5
area = length * width

print("Length:", length)
print("Width:", width)
print("Area:", area)

Variables make complex calculations easier to understand:

# Using variables in more complex calculations
price = 29.99
tax_rate = 0.08
tax_amount = price * tax_rate
total = price + tax_amount

print("Price:", price)
print("Tax rate:", tax_rate)
print("Tax amount:", tax_amount)
print("Total:", total)

You can build variables from other variables:

# Variables can use other variables
first_number = 15
second_number = 25
sum_result = first_number + second_number
average = sum_result / 2

print("First number:", first_number)
print("Second number:", second_number)
print("Sum:", sum_result)
print("Average:", average)

Exercise: Calculate Circle Properties

Given a circle's radius, calculate its diameter and area. Use variables to store the radius (5), diameter (radius * 2), and area (radius * radius * 3.14159).

# TODO: Create a variable called radius and assign it the value 5 # TODO: Create a variable called diameter that equals radius * 2 # TODO: Create a variable called area that equals radius * radius * 3.14159 # TODO: Print all three values with appropriate labels

5. String Variables and Text Operations

String variables (text) have special capabilities. You can combine them, repeat them, and perform other text operations.

# Combining strings
first_name = "John"
last_name = "Smith"
full_name = first_name + " " + last_name

print("First name:", first_name)
print("Last name:", last_name)
print("Full name:", full_name)

You can repeat strings using the multiplication operator:

# Repeating strings
star = "*"
line = star * 20
greeting = "Hello! "
repeated_greeting = greeting * 3

print("Single star:", star)
print("Line of stars:", line)
print("Single greeting:", greeting)
print("Repeated greeting:", repeated_greeting)

When combining strings with numbers, convert numbers to text first:

# Mixing strings and other operations
item = "apple"
count = 5
message = "I have " + str(count) + " " + item + "s"

print("Item:", item)
print("Count:", count)
print("Message:", message)

Notice that we used str(count) to convert the number to text before combining it with other strings. This is necessary because Python can't directly combine numbers and text with the + operator.

Exercise: Create a Personalized Message

Create variables for a person's name and their age, then create a personalized birthday message that combines them.

# TODO: Create a variable called name and assign it "Sarah" # TODO: Create a variable called age and assign it 25 # TODO: Create a message that says "Happy birthday, " + name + "!" # TODO: Create an age_message that says "You are now " + age + " years old." # TODO: Create a wish that says "Hope you have a wonderful day!" # TODO: Print all three messages

6. Common Variable Mistakes

Let's look at common mistakes beginners make with variables so you can avoid them:

# Common mistakes and corrections:

# 1. Using a variable before defining it
# print(undefined_variable)  # This would cause an error

# Correct: define first, then use
my_variable = "Hello"
print(my_variable)

# 2. Forgetting quotes for text
correct_text = "This is text"
# incorrect_text = This is text  # This would cause an error

print("Correct text:", correct_text)

# 3. Using reserved words as variable names
# print = "Hello"  # This would break the print function!

# Correct: use descriptive names that aren't reserved
message = "Hello"
print("Message:", message)

# 4. Inconsistent variable names
user_name = "Alice"
# Later in code, accidentally using different name:
# print(username)  # This would cause an error (missing underscore)

print("User name:", user_name)  # Correct: match the exact name

# 5. Mixing up assignment (=) with comparison (==)
value = 10  # Assignment: store 10 in value
print("Value:", value)
# Later we'll learn about comparison: value == 10

Exercise: Fix the Variable Errors

The code below has several variable-related errors. Fix them so the program runs correctly and prints information about a student.

# The code below has errors - fix them: # TODO: Fix the variable name (should be student_name) # studentName = "Emma Wilson" # TODO: Fix the missing quotes around the grade # student_grade = A # TODO: Fix the variable name to be consistent (should be points_earned) # pointsEarned = 95 # TODO: Fix the print statements to use correct variable names # print("Student:", student_name) # print("Grade:", student_grade) # print("Points:", points_earned)

🎯 Bring It All Together: A Student Information System

Let's create a more comprehensive example that uses multiple variables to store and display student information.

# Complete student information system
student_id = 12345
first_name = "Maria"
last_name = "Garcia"
full_name = first_name + " " + last_name

# Course information
course_name = "Introduction to Python"
semester = "Fall 2024"
credits = 3

# Grade information
assignments_completed = 8
total_assignments = 10
current_grade = 87.5
letter_grade = "B+"

# Calculate completion percentage
completion_percentage = (assignments_completed / total_assignments) * 100

# Display all information
print("=" * 40)
print("STUDENT INFORMATION SYSTEM")
print("=" * 40)
print("Student ID:", student_id)
print("Name:", full_name)
print()

print("COURSE INFORMATION:")
print("Course:", course_name)
print("Semester:", semester)
print("Credits:", credits)
print()

print("GRADE INFORMATION:")
print("Assignments completed:", assignments_completed, "out of", total_assignments)
print("Completion percentage:", completion_percentage, "%")
print("Current grade:", current_grade)
print("Letter grade:", letter_grade)
print()

print("Keep up the great work,", first_name + "!")

Final Exercise: Create a Product Inventory System

Create a simple inventory system for a store item. Include product name, price, quantity in stock, and total value (price * quantity).

# TODO: Create variables for product_name, price, quantity, and status # TODO: Calculate total_value as price * quantity # TODO: Print a formatted inventory report as shown in the expected output

📝 What You've Learned

Congratulations! You now understand how to work with variables in Python:

Variables are the foundation of programming - they let you store, modify, and reuse information throughout your program. Master variables, and you're well on your way to writing powerful Python programs!

Next Steps

Now that you can store information in variables, the next step is learning how to perform calculations and operations with that data using math operators!