4. Variables and Naming Conventions
Level: BeginnerDuration: 24m
What Are Variables?
Variables are like containers used to store information in your program. You give them a name, assign them a value, and then use them later.
python
message = "Welcome to Python!"
score = 100
pi = 3.14đź’ˇ Think of variables as labeled boxes where you store data.
How Assignment Works
The equals sign `=` assigns a value to a variable. You can change the value at any time.
python
status = "online"
print(status) # online
status = "offline"
print(status) # offlineVariable Naming Rules
- Variable names must start with a letter or underscore (_)—not a number.
- Use only letters, numbers, and underscores (no spaces or symbols).
- Names are case-sensitive (`age` ≠`Age`).
- Don’t use Python keywords like `class`, `for`, `if`.
| Valid Names | Invalid Names | |
|---|---|---|
| name, total_price, _count | 2name, first-name, class | |
| user_name, is_active | user name, total$ | for |
Naming Conventions (Best Practice)
Writing clean code starts with using meaningful variable names. Follow Python’s style guide (PEP 8):
- Use snake_case: `user_age`, `total_amount`
- Use descriptive names: `price_per_item` (not `ppi`)
- Booleans should sound like True/False: `is_valid`, `has_access`
python
# Good
user_name = "Grace"
is_logged_in = True
# Bad
x = "Grace"
flag = TrueMultiple Assignments
Python allows assigning multiple variables in one line.
python
x, y, z = 10, 20, 30
name = city = "Lagos" # same value for multiple variablesConstants in Python
Python doesn’t have true constants, but by convention, variables written in UPPERCASE are treated as constants.
python
PI = 3.14159
MAX_CONNECTIONS = 5Mini Project Step
Add a new file called bank_account.py. Create variables for account holder name, account number, account balance, and bank name. Follow Python naming conventions and print the values in a formatted sentence.