Lesson: Defining Variables in Python
Objective:
Understand how to create and use variables to store data in Python.
1. What is a Variable?
A variable is a named container that holds data (values). Think of it like a labeled box:
- The label is the variable name.
- The content is the value stored inside.
Why use variables?
- Reuse data without repeating values.
- Make code readable (e.g.,
total_price instead of 25.99 * 0.8).
- Dynamically update values (e.g.,
score = score + 10).
2. Assigning Values to Variables
Use = to assign a value to a variable.
python
# Syntax: variable_name = value
age = 25
name = "Alice"
is_student = True
pi = 3.14
Example:
python
message = "Hello, World!" # Assigns the string to `message`
print(message) # Output: Hello, World!
3. Variable Naming Rules
| Rule | Valid Example | Invalid Example |
|---|
Start with a letter or _ | _count, name | 2nd_place |
Follow with letters, numbers, or _ | total_sum, user1 | user@ |
Case-sensitive (A ≠ a) | Age vs age | — |
Avoid Python keywords (e.g., if, for) | user_input | for |
Conventions:
- Use snake_case (e.g.,
user_age, total_cost).
- Make names descriptive (e.g.,
first_name instead of fn).
4. Dynamic Typing
Python variables dynamically change type based on their assigned value.
python
x = 10 # x is an integer
x = "Python" # Now x is a string
x = True # Now x is a boolean
5. Multiple Assignment
Assign multiple variables in one line:
python
# Assign three variables at once
a, b, c = 5, 10, 15
# Assign the same value to multiple variables
x = y = z = 0
6. Practice Exercises
-
Basic Assignment:
- Create a variable
country storing your country’s name.
- Create a variable
population storing its population (in millions).
- Print both.
-
Dynamic Typing Demo:
- Assign
100 to a variable data.
- Reassign
data to "Python".
- Print
data after each step.
-
Multiple Assignment:
- Use one line to set
color = "red", fruit = "apple", and price = 1.99.
- Print all three.
7. Key Takeaways
- Variables store data using
=.
- Names must follow rules (start with letter/
_, no keywords).
- Python variables dynamically change type.
- Use snake_case for readability.
8. Common Pitfalls
❌ Misspelled Names:
python
message = "Hi"
print(mesage) # Error: 'mesage' is undefined!
❌ Using Keywords:
python
class = "Biology" # SyntaxError! 'class' is a keyword.
❌ Uninitialized Variables:
python
print(age) # Error: 'age' not defined before use!
Next Steps: Try modifying variables (e.g., counter = counter + 1) and explore data types (integers, strings, booleans).