Python variables are one of the fundamental concepts you’ll need to master when learning Python programming. In this detailed tutorial, we will explore Python variables deeply, covering everything from basics to best practices.
1. What is a Variable?
A variable in Python is a reserved memory location that stores a value. You can think of it as a labeled box in which you can store data (like numbers, text, or more complex structures).
age = 30
name = "John"
is_student = False
2. Declaring and Assigning Variables
In Python, you don’t have to explicitly declare variables. The variable is created when you assign a value to it.
x = 10 # integer assignment
y = 3.14 # float assignment
message = "Hello, Python!" # string assignment
3. Rules and Conventions for Variable Naming (Reminder)
Variable names in Python must follow specific rules:
- They can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
- Must begin with a letter or underscore (_), never a digit.
- Case sensitive (
Age
andage
are different).
Valid examples:
user_age = 25
_age = "hidden"
UserAge = 25
userAge = 25
Invalid examples:
2user = 25 # starts with a digit
user-age = 25 # contains hyphen
Conventions: Python recommends using snake_case
for variables:
4. Dynamic Typing in Python
Python variables are dynamically typed, meaning a single variable can hold different types of data during its lifetime.
var = 10
print(var) # Outputs: 10
var = "Python"
print(var) # Outputs: Python
5. Reassigning Variables
Python allows you to easily reassign variables to new values.
x = 5
print(x) # Outputs: 5
x = 15
print(x) # Outputs: 15
6. Multiple Assignment
Python also supports assigning values to multiple variables in one line.
Example 1: Different values
x, y, z = 1, 2, 3
print(x, y, z) # Outputs: 1 2 3
Example 2: Same value
a = b = c = 0
print(a, b, c) # Outputs: 0 0 0
7. Delete Assignment
Use the del
keyword to remove variables explicitly.
var = 10
print(var) # Outputs: 10
del var
# print(var) # Error: var is not defined anymore
Common Mistakes
Mistake #1: Undefined Variables
Trying to use a variable before assigning it:
# print(count) # Error: count is not defined
count = 0
Mistake #2: Typo in Variable Name
my_var = 10
# print(myVar) # Error: NameError due to typo
Mistake #3: Misunderstanding Variable Scope
def function():
x = 5
function()
# print(x) # Error: x is local to function()