Skip to content

Variables & Data Types

Python is dynamically typed โ€” you donโ€™t declare a type, the interpreter infers it at runtime.

name = "Alice"
age = 30
price = 9.99
is_active = True
nothing = None
CategoryTypes
Textstr
Numericint, float, complex
Booleanbool
Sequencelist, tuple, range
Mappingdict
Setset, frozenset
Binarybytes, bytearray, memoryview
NoneNoneType
x = 42
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
# Implicit
result = 5 + 2.0 # float: 7.0
# Explicit
n = int("42") # 42
f = float("3.14") # 3.14
s = str(100) # "100"
b = bool(0) # False
lst = list("abc") # ['a', 'b', 'c']
a = b = c = 0
x, y, z = 1, 2, 3
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]

Python has no const keyword. Use ALL_CAPS by convention:

MAX_SIZE = 100
PI = 3.14159
  • Variables defined inside a function are local.
  • Variables defined at module level are global.
  • Use global keyword to modify a global inside a function.
count = 0
def increment():
global count
count += 1
# Mutable default โ€” avoid this
def append_item(item, lst=[]): # BAD: lst shared across calls
lst.append(item)
return lst
# Safe version
def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst