Notes › Python
Python Basics
Python is a high-level, interpreted language with clean syntax — used for scripting, web backends (Django, Flask), data science, AI and coding interviews.
Variables and types
Python is dynamically typed — no type declarations.
name = "Asha" # str
age = 21 # int (no size limit!)
cgpa = 8.4 # float
placed = False # bool
nothing = None # NoneType
print(type(age)) # <class 'int'>
x, y = 10, 20 # multiple assignment
x, y = y, x # swap
| Type | Mutable? | Example |
|---|---|---|
int, float, bool, str |
❌ | 5, 3.14, True, "hi" |
tuple |
❌ | (1, 2) |
list |
✅ | [1, 2, 3] |
dict |
✅ | {"a": 1} |
set |
✅ | {1, 2} |
Input and output
n = int(input()) # one integer
a = list(map(int, input().split())) # a line of integers
print("Sum:", sum(a))
print(f"{name} is {age} years old") # f-string
print(*a) # 1 2 3 (space separated)
For big inputs in competitive programming: import sys; input = sys.stdin.readline.
Operators
7 / 2 # 3.5 true division
7 // 2 # 3 floor division
7 % 2 # 1
2 ** 10 # 1024 power
-7 // 2 # -4 floors towards −∞
and, or, not for logic; == compares values, is compares identity (use is None).
Conditions and loops
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
else:
grade = "C"
for i in range(5): # 0..4
print(i)
for i in range(10, 0, -2): # 10 8 6 4 2
print(i)
for i, v in enumerate(["a", "b"]):
print(i, v)
for a, b in zip([1, 2], ["x", "y"]):
print(a, b)
while n > 0:
n //= 10
result = "even" if n % 2 == 0 else "odd" # ternary
break, continue, and for ... else (the else runs if the loop did not break).
Functions
def area(l, w=1): # default argument
"""Return the area of a rectangle."""
return l * w
area(5) # 5
area(w=2, l=3) # 6 (keyword arguments)
def total(*args): # any number of positional args → tuple
return sum(args)
def show(**kwargs): # any keyword args → dict
for k, v in kwargs.items():
print(k, v)
square = lambda x: x * x # small anonymous function
Functions are objects — they can be passed around (sorted(words, key=len)).
Scope
LEGB rule: Local → Enclosing → Global → Built-in. Use global x to assign a global inside a function, nonlocal x for an enclosing function's variable.
Common mistakes
def add(item, items=[]): # ❌ the default list is shared between calls
items.append(item)
return items
def add(item, items=None): # ✅
if items is None:
items = []
items.append(item)
return items
a = b = []makes one list with two names.- Indentation is part of the syntax — mixing tabs and spaces breaks code.
int("3.5")fails; usefloat()first.
Interview one-liners
- Python is interpreted (compiled to bytecode, run by the CPython VM) and dynamically typed.
- List vs tuple: mutable vs immutable; tuples can be dict keys.
isvs==: identity vs equality.- Everything is an object; variables are names bound to objects.
- GIL (Global Interpreter Lock): in CPython only one thread runs Python bytecode at a time → use multiprocessing for CPU-heavy work.
- Next: Python Lists, Dicts and Sets, OOP in Python.