Python Variables - including theory, types, edge cases, memory, naming conventions, user input, unpacking, scope, mutation, and more.
Table of Contents
- What is a Variable?
- Variable Naming Rules
- Assigning Values
- Data Types
- Type Casting
- Multiple Assignments
- Unpacking Sequences
- Constants
- User Input and Variables
- Variable Scope (Local, Global, Nonlocal)
- Mutable vs Immutable Variables
- Memory Management
- Deleting Variables
- Useful Functions with Variables
- Edge Cases and Pitfalls
- Practice Exercises
1. What is a Variable?
A variable is a named reference to a location in memory where data is stored.
Examples:
x = 10
name = "Alice"
height = 5.9
is_admin = True
2. Variable Naming Rules
Valid:
- Start with a letter or underscore.
- Contain letters, numbers, and underscores.
- Case-sensitive.
Invalid:
- Cannot start with a number.
- Cannot use Python keywords (
for,if,while, etc).
Examples:
_my_var = 1
userName = "Tom"
score123 = 45
Invalid:
1score = 10 # Error
for = 5 # 'for' is a keyword
3. Assigning Values
Basic:
x = 5
y = "Hello"
Chain Assignment:
a = b = c = 100
Simultaneous Assignment:
x, y = 1, 2
Swapping:
a, b = b, a
4. Data Types in Variables
| Type | Example |
|---|---|
int | x = 10 |
float | pi = 3.14 |
str | name = "Alice" |
bool | is_valid = True |
list | nums = [1, 2, 3] |
tuple | t = (1, 2) |
dict | d = {"a": 1} |
set | s = {1, 2, 3} |
None | x = None |
Use type() to find a variable's data type:
print(type(x)) # <class 'int'>
5. Type Casting
Convert one type to another.
Examples:
a = "100"
b = int(a) # String to int
c = float(b) # Int to float
d = str(c) # Float to string
Common Pitfall:
x = int("10.5") # ValueError: invalid literal
6. Multiple Assignments
a, b, c = 1, 2, 3
x = y = z = "same"
With operations:
x, y = y, x + y
7. Unpacking Sequences
Python allows sequence unpacking into variables.
Tuple or List:
data = [10, 20, 30]
a, b, c = data
Extended Unpacking:
a, *b, c = [1, 2, 3, 4, 5]
# a=1, b=[2,3,4], c=5
8. Constants in Python
Python doesn't have built-in constants. Use uppercase to signify that a variable is constant.
PI = 3.14159
MAX_USERS = 100
9. User Input and Variables
name = input("Enter your name: ") # Always returns string
age = int(input("Enter your age: ")) # Convert input to int
price = float(input("Enter price: ")) # Convert input to float
Example:
n1 = int(input("Enter 1st number: "))
n2 = int(input("Enter 2nd number: "))
print("Sum:", n1 + n2)
10. Variable Scope
Global Variable:
x = 10
def show():
print(x)
show() # 10
Local Variable:
def func():
x = 5
print(x)
func() # 5
Changing Global:
x = 5
def update():
global x
x = 20
update()
print(x) # 20
nonlocal Keyword:
Used inside nested functions.
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x) # 20
11. Mutable vs Immutable Variables
Immutable:
int, float, str, bool, tuple
x = 10
y = x
y += 1
print(x, y) # 10, 11
Mutable:
list, dict, set
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3] — affected!
Use copy() to prevent this:
b = a.copy()
12. Memory Management
Python manages memory using reference counting and garbage collection.
Use id() to get memory location:
x = 100
print(id(x)) # Memory address
13. Deleting Variables
x = 10
del x
# print(x) # NameError
14. Useful Functions with Variables
# type() → data type
print(type(10)) # <class 'int'>
# isinstance() → check type
print(isinstance(10, int)) # True
# id() → memory location
print(id("hello"))
15. Edge Cases and Pitfalls
Assigning Mutable Defaults in Functions
def add_item(item, container=[]):
container.append(item)
return container
print(add_item("A")) # ['A']
print(add_item("B")) # ['A', 'B'] ❗ Unexpected!
Use this instead:
def add_item(item, container=None):
if container is None:
container = []
container.append(item)
return container
16. Practice Exercises
Exercise 1:
Write a program that takes name and age and prints them.
name = input("Name: ")
age = int(input("Age: "))
print(f"{name} is {age} years old.")
Exercise 2:
Swap two variables without a temp variable.
x, y = 5, 10
x, y = y, x
Exercise 3:
Create a program to input 3 numbers and output the average.
a = float(input("Enter 1st: "))
b = float(input("Enter 2nd: "))
c = float(input("Enter 3rd: "))
avg = (a + b + c) / 3
print("Average:", avg)
Summary Table
| Concept | Example |
|---|---|
| Assignment | x = 10 |
| Multiple Assignments | x, y = 1, 2 |
| Unpacking | a, *b, c = [1,2,3,4,5] |
| Constants | MAX_LIMIT = 100 |
| Input | input("Name?") |
| Type Conversion | int("100"), str(10) |
| Mutable Types | list, dict, set |
| Immutable Types | int, float, str, tuple |
| Scope Types | Global, Local, Nonlocal |