Variables
Python variables require no type declaration — just assign a value. This flexibility is powerful but requires discipline in naming and type awareness.
Assignment is Declaration
In Python, you create a variable by assigning a value. There is no var, int, or String keyword. Python infers the type from the value.
# All of these create and initialise a variable:
name = "Thandi Mokoena"
age = 22
mark = 74.5
enrolled = True
address = None # None is Python's equivalent of null
print(name)
print(f"Age: {age}, Mark: {mark}%, Enrolled: {enrolled}")
Dynamic Typing
A Python variable can be reassigned to a completely different type at runtime. This is called dynamic typing. It gives flexibility but requires care — accidentally assigning the wrong type to a variable is a common source of bugs.
x = 42 # x is int
print(type(x)) # <class 'int'>
x = "hello" # x is now str — perfectly valid in Python
print(type(x)) # <class 'str'>
x = [1, 2, 3] # x is now list
print(type(x)) # <class 'list'>
# Type hints — optional but recommended for clarity:
from typing import Optional
name: str = "Sipho"
age: int = 24
mark: float = 81.0
active: bool = True
notes: Optional[str] = None # may be str or None
Multiple Assignment
# Assign the same value to multiple variables:
a = b = c = 0
# Assign different values on one line (tuple unpacking):
x, y, z = 10, 20, 30
print(x, y, z) # 10 20 30
# Swap without a temp variable (idiomatic Python):
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
# Underscore for values you don't need:
first, _, last = (1, 2, 3)
print(first, last) # 1 3
# Extended unpacking with *:
head, *tail = [1, 2, 3, 4, 5]
print(head) # 1
print(tail) # [2, 3, 4, 5]
Naming Conventions (PEP 8)
- Variables and functions — snake_case:
first_name,total_score,is_enrolled. - Classes — PascalCase:
LearnerProfile,BankAccount. - Constants — UPPER_SNAKE_CASE:
VAT_RATE,MAX_RETRIES. - Private — _single_underscore:
_internal_counter. - Very private — __double_underscore:
__secret(name-mangled).
Practice Task
Your Turn
Create variables for: your full name (str), age (int), city (str), course (str), GPA (float), whether you have a laptop (bool), and an optional scholarship amount (could be None or a float). Use type hints on all of them. Use extended unpacking to split a list of 5 marks into the first mark and the rest. Print everything with f-strings.
Common Mistakes
- Variables are case-sensitive —
Nameandnameare different. - Starting a variable name with a digit —
1st_placeis a SyntaxError. - Using Python keywords as names —
list,type,printare valid names but shadow built-ins. - Reassigning a variable to an incompatible type by accident — type hints help IDEs catch this.
Professional Tip
Descriptive snake_case names are Pythonic. number_of_enrolled_learners over n. Your future self and colleagues will thank you.
Mini Quiz
What naming convention do Python variables and functions use?