Learn Without Walls
← Module 2 Home Lesson 1 of 4 Next Lesson →

Variables and Assignment

What You'll Learn

1. What is a Variable?

Variable: A variable is a name that refers to a value stored in your computer's memory. Think of it as a labeled container that holds a piece of data.

In everyday life, you use labels all the time. A contact in your phone labeled "Mom" holds a phone number. A folder on your desktop labeled "Homework" holds files. Variables work the same way in programming -- they give names to data so you can find and use it later.

In Python, you create a variable using the assignment operator (=):

age = 25
name = "Alice"
temperature = 98.6

When Python sees age = 25, it creates a space in memory, stores the value 25 there, and labels it age. From that point on, whenever you use age in your code, Python knows you mean 25.

age = 25
print(age)
25

Real-World Analogy

Imagine a row of mailboxes. Each mailbox has a label (the variable name) and contains mail (the data). You can look at the label to find the right mailbox, take out the mail, or replace it with new mail.

2. Creating Variables with Assignment

The assignment operator = works from right to left. Python first evaluates the value on the right side, then stores it in the variable on the left side.

# Python evaluates the right side first, then assigns to the left
x = 10          # Store 10 in x
y = 3 + 7       # Evaluate 3 + 7 = 10, store in y
z = x + y       # Evaluate x + y = 20, store in z

print(x)
print(y)
print(z)
10 10 20
Important: The = sign in Python is NOT the same as the equals sign in math. In math, x = 5 means "x equals 5." In Python, x = 5 means "assign the value 5 to the variable x." The arrow of information goes from right to left.

You can also create multiple variables at once:

# Multiple assignments on separate lines
first_name = "Alice"
last_name = "Smith"
age = 25

# Multiple assignments on one line (less common, but valid)
a, b, c = 1, 2, 3
print(a, b, c)
1 2 3

3. Variable Naming Rules

Python has strict rules about what you can name your variables. If you break these rules, Python will give you an error.

Python Variable Naming Rules:
  1. Must start with a letter (a-z, A-Z) or an underscore (_)
  2. Can contain letters, numbers, and underscores
  3. Cannot contain spaces or special characters (!, @, #, $, etc.)
  4. Cannot be a Python keyword (reserved word)
  5. Are case-sensitive (Name and name are different variables)
# VALID variable names
age = 25
first_name = "Alice"
_private = 42
item2 = "banana"
MAX_SIZE = 100

# INVALID variable names (these cause errors!)
# 2nd_place = "Silver"    # Cannot start with a number
# first name = "Alice"    # Cannot contain spaces
# my-var = 10             # Cannot contain hyphens
# class = "Math"          # 'class' is a reserved keyword

Python has about 35 reserved keywords that you cannot use as variable names. Some common ones include: if, else, for, while, True, False, None, and, or, not, class, def, return, import.

Case Sensitivity in Action

Name = "Alice"
name = "Bob"
NAME = "Charlie"

print(Name)
print(name)
print(NAME)
Alice Bob Charlie

These are three completely separate variables! Be careful with capitalization.

4. Naming Conventions (Best Practices)

While Python's rules tell you what you can do, conventions tell you what you should do. Following conventions makes your code easier to read.

snake_case: The Python convention for variable names. Use lowercase letters with underscores separating words: student_grade, total_price, first_name.
# Good: snake_case (Python convention)
student_name = "Alice"
total_price = 29.99
is_enrolled = True

# Avoid: other styles (valid but not Pythonic)
studentName = "Alice"      # camelCase - used in JavaScript
StudentName = "Alice"      # PascalCase - used for class names
STUDENT_NAME = "Alice"     # ALL_CAPS - used for constants

5. Reassigning Variables

One of the most powerful features of variables is that you can change their values at any time. When you assign a new value to an existing variable, the old value is replaced.

score = 0
print("Starting score:", score)

score = 10
print("After earning points:", score)

score = score + 5
print("After bonus:", score)
Starting score: 0 After earning points: 10 After bonus: 15

The line score = score + 5 might look strange mathematically, but remember that = means assignment. Python evaluates the right side first (score + 5 = 10 + 5 = 15), then stores that result back in score.

Python also lets you change the type of data a variable holds:

my_var = 42           # my_var holds an integer
print(my_var)

my_var = "hello"      # now my_var holds a string
print(my_var)
42 hello
Tip: While Python allows you to change a variable's type, doing so can make your code confusing. It is generally best practice to keep a variable holding the same type of data throughout your program.

6. Choosing Meaningful Variable Names

Good variable names make your code read almost like English. Compare these two versions of the same program:

Hard to Understand

x = 40
y = 15.50
z = x * y
print(z)

Easy to Understand

hours_worked = 40
hourly_rate = 15.50
weekly_pay = hours_worked * hourly_rate
print(weekly_pay)
620.0

Both programs produce the same result, but the second one tells a story. You can immediately understand what the program calculates without any comments.

Guidelines for choosing good names:

Check Your Understanding

Question 1: Which of the following are valid Python variable names?

my_name, 2fast, _count, total price, class, itemA

Valid: my_name, _count, itemA

Invalid: 2fast (starts with number), total price (contains space), class (reserved keyword)

Question 2: What will this code print?

x = 5
x = x + 3
x = x * 2
print(x)

Answer: 16

Step by step: x starts as 5, then x = 5 + 3 = 8, then x = 8 * 2 = 16.

Try It Yourself!

Open Python on your computer and try these exercises:

  1. Create variables for your name, age, and favorite color. Print each one.
  2. Create two number variables and print their sum, difference, and product.
  3. Create a variable called counter set to 0, then add 1 to it three times using reassignment. Print the final value.

Key Takeaways

← Module 2 Home Next: Numbers →