Variables and Assignment
What You'll Learn
- What a variable is and why we use them
- How to create variables with the assignment operator (
=) - Python's variable naming rules and conventions
- How to reassign variables to new values
- How to choose meaningful, readable variable names
1. What is a Variable?
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)
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)
= 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)
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.
- Must start with a letter (a-z, A-Z) or an underscore (_)
- Can contain letters, numbers, and underscores
- Cannot contain spaces or special characters (!, @, #, $, etc.)
- Cannot be a Python keyword (reserved word)
- Are case-sensitive (
Nameandnameare 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)
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.
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)
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)
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)
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:
- Use descriptive names:
student_countinstead ofsc - Avoid single letters except for simple loop counters
- Use nouns for data:
temperature,name,total - Use verb phrases for booleans:
is_valid,has_permission - Keep names reasonably short but clear
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:
- Create variables for your name, age, and favorite color. Print each one.
- Create two number variables and print their sum, difference, and product.
- Create a variable called
counterset to 0, then add 1 to it three times using reassignment. Print the final value.
Key Takeaways
- A variable is a named container for storing data in memory.
- Use the assignment operator (
=) to create or update variables. - Variable names must follow Python's rules: start with a letter or underscore, no spaces or special characters.
- Use snake_case for variable names (Python convention).
- Variables can be reassigned to new values at any time.
- Choose meaningful names that describe the data they hold.