2.4 Variables: Declarations, Assignments, Naming
Understanding the role of variables as "containers" for storing data. We will look at Python's dynamic typing, multiple assignments, and naming conventions.
Variables are names we use to refer to data values stored in the computer's memory. You can think of them as labels we stick on "boxes" that contain data. Assigning a value to a variable is done with the assignment operator `=`.
Dynamic Typing
One of the features that make Python beginner-friendly is dynamic typing. This means you don't need to declare the type of the variable (e.g., int, str) beforehand. Python automatically determines the variable's type at the time of assignment. This allows you to change a variable's type by assigning it a new value of a different type.
# Dynamic typing in practice
my_var = 10 # my_var is now of type int
print(f"my_var: {my_var}, Type: {type(my_var).__name__}")
my_var = "Hello" # Now the same variable points to a value of type str
print(f"my_var: {my_var}, Type: {type(my_var).__name__}")
my_var = True # And now it's of type bool
print(f"my_var: {my_var}, Type: {type(my_var).__name__}")
Naming Rules and Conventions (PEP 8)
There are rules and conventions for how we name variables:
- Names must begin with a letter (a-z, A-Z) or an underscore (_).
- The rest of the name can contain letters, numbers (0-9), and underscores.
- Names are case-sensitive (e.g., `age` and `Age` are two different variables).
- You cannot use Python keywords (e.g., `if`, `for`, `class`) as variable names.
Tip!
The official Python style guide, known as PEP 8, recommends using `snake_case` for variable and function names. This means lowercase letters with words separated by underscores (e.g., `user_name`, `total_price`). This makes the code more readable.
Multiple Assignments
Python offers a concise way to assign values to multiple variables simultaneously, whether it's the same value or different ones.
# Assigning the same value to multiple variables
x = y = z = 10
print(f"x={x}, y={y}, z={z}")
# Assigning different values (unpacking)
# This works for any sequence (e.g., list, tuple)
name, age, city = "Kostas", 35, "Patras"
print(f"Name: {name}, Age: {age}, City: {city}")
# A clever way to swap values between two variables
a = 5
b = 10
print(f"Initially: a={a}, b={b}")
a, b = b, a # Swapping values
print(f"After swapping: a={a}, b={b}")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.