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:
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:
Create variables to store information about yourself or a fictional character. Include a name, age, and favorite color.
Python has specific rules for variable names. Following these rules prevents errors and makes your code easier to read:
name
, _private
user_name2
, total_cost
2names
is invalidName
and name
are different variablesprint
, if
, for
, etc.# 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)
Create variables with descriptive names for a recipe. Include the recipe name, number of servings, and cooking time in minutes.
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!
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.
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)
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).
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.
Create variables for a person's name and their age, then create a personalized birthday message that combines them.
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
The code below has several variable-related errors. Fix them so the program runs correctly and prints information about a student.
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 + "!")
Create a simple inventory system for a store item. Include product name, price, quantity in stock, and total value (price * quantity).
Congratulations! You now understand how to work with variables in Python:
variable_name = value
+
, repeating with *
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!
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!