Variables in Python
Variables in Python are simple to create and use. Python is dynamically typed, meaning you don't need to declare variable types.
Creating Variables: Simply assign a value with the = operator.
Naming Rules:
- Must start with a letter or underscore
- Can contain letters, numbers, underscores
- Case-sensitive (name and Name are different)
- Cannot use reserved words
Naming Conventions:
- Use snake_case for variables and functions
- Use UPPER_CASE for constants
- Use PascalCase for classes
- Be descriptive: user_email instead of e
Multiple Assignment: Python allows assigning multiple variables at once.
Type Hints (Python 3.5+): Optional type annotations for better code documentation.
Code Examples
Variable Basicspython
# Simple variable assignment
name = "Alice"
age = 30
is_student = False
height = 5.7
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Student: {is_student}")
print(f"Height: {height}")
# Multiple assignment
x, y, z = 1, 2, 3
print(f"x={x}, y={y}, z={z}")
# Same value to multiple variables
a = b = c = 0
print(f"a={a}, b={b}, c={c}")
# Swapping variables (Python magic!)
x, y = y, x
print(f"After swap: x={x}, y={y}")
# Type hints (optional but recommended)
user_name: str = "Bob"
user_age: int = 25
is_active: bool = True
# Check variable type
print(f"Type of name: {type(name)}")
print(f"Type of age: {type(age)}")Python's dynamic typing makes it easy to work with variables. Type hints add documentation without runtime checking.
Quick Quiz
1. What naming convention does Python use for variables?
2. How do you swap two variables in Python?
Was this lesson helpful?