Variable Assignment
Learn to store and manipulate data using Python variables
Variables are fundamental to programmingβthey act as labeled containers that store data values in your computer's memory. In Python, variables are created the moment you first assign a value to them.
π Concepts & Theory
A variable in Python is created using the assignment operator (=). The variable name goes on the left, and the value goes on the right.
Variable Naming Rules
- Must start with a letter or underscore (_)
- Can contain letters, numbers, and underscores
- Case-sensitive (
nameβNameβNAME) - Cannot be Python keywords (if, for, class, etc.)
Naming Conventions (PEP 8)
- Use lowercase with underscores:
user_name,total_count - Be descriptive:
ageinstead ofa - Constants in ALL_CAPS:
MAX_SIZE,PI
Data Types
name = "Alice" # String (str)
age = 25 # Integer (int)
height = 5.6 # Float (float)
is_student = True # Boolean (bool)
Multiple Assignment
x = y = z = 0 # Same value to multiple variables
a, b, c = 1, 2, 3 # Multiple values at once
name, age = "Bob", 30 # Mixed types
Dynamic Typing
Python figures out the type automatically. You can even change a variable's type:
x = 10 # x is an integer
x = "ten" # x is now a string π― Your Challenge
Create two variables: one called "name" containing a string, and one called "age" containing an integer. Then print both values using a single print() statement.
π Starter Code
name = ""
age = 0
print(name, age)
- Use = for assignment (variable = value)
- Strings need quotes, numbers don't
- print() can display multiple values separated by commas
Solution
name = "Alice"
age = 25
print(name, age)
Explanation
This solution creates two variables: name stores a string (text in quotes), age stores an integer (whole number). The print() function accepts multiple arguments separated by commas.
β οΈ Common Mistakes to Avoid
- Putting numbers in quotes ("25" instead of 25)
- Using spaces in variable names (my name instead of my_name)
- Starting variable names with numbers
- Forgetting quotes around strings