Learn Python variables with this beginner-friendly guide. Understand variable basics, naming rules (including valid vs invalid names), reserved keywords, and practice with hands-on coding tasks.
Purpose: Variables provide a way to store and manage data that can be used and manipulated throughout a program. They make programs more flexible and allow for dynamic data storage.
Assignment statement: in Python is used to assign a value to a variable. Its primary purpose is to store and manage data within a program.
Imagine variables as labeled boxes:
Example:
name = "Alice" # Stores text
age = 25 # Stores a number
is_student = True # Stores True/False
=)Use = to assign values. No need to declare types!
Key Rules:
x = 10
x = "hello" # Now x is a string!
a, b = 1, 2 # a=1, b=2
x = y = z = 0 # All set to 0
x, y = 10, 20
x, y = y, x # Swap! (Now x=20, y=10)
Common Mistakes:
user name = "Bob" β2nd_place = "Silver" βIn Python, valid variable names must adhere to the following rules:
a-z, A-Z)0-9) but not as the first character_)age, Age, and AGE are different).snake_case (recommended Python style).Examples:
name = "Alice"
user_age = 25
_total = 100
item2 = "book"
!, @, #, etc.).Examples:
2name = "Bob" # Error: Starts with digit
first-name = "John" # Error: Hyphen not allowed
user age = 30 # Error: Contains space
Python has 35 reserved keywords (e.g., if, for, while).
Check All Keywords:
import keyword
print(keyword.kwlist)
β οΈ Never use these as variable names!
| Valid β
| Invalid β |
|ββββββ-|βββββββ|
| user_name | user-name (hyphen)|
| _total | 2nd_place (starts with digit)|
| price2 | class (reserved keyword)|
π‘ Tip:
If you accidentally use a keyword, Python will raise a SyntaxError:
class = "Biology" # Error: 'class' is a keyword
Which of these are valid?
1. user_name
2. 3rd_place
3. return
4. _price
5. my-var
β Use descriptive names (e.g., student_count vs. n).
β Stick to snake_case (e.g., total_score).
β Avoid single letters (except in loops like for i in range(5)).
Given:
length = 10
width = 5
Your Task: Calculate and print:
length * width)2 * (length + width))type() and id()Code:
x = 10
print(type(x)) # Output: <class 'int'>
print(id(x)) # Output: Memory address
Questions:
x = "hello" and check type(x)?y = 10. Does id(y) match id(x)? Why?π‘ Hint: Python reuses memory for small integers!
π Additional Resources: