Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Python Documentation

Simple, readable and everywhere — scripting, web backends, data science, AI and automation.

Python is a high-level, general-purpose language known for clean, readable syntax. It is used for scripting, web backends (Django, Flask, FastAPI), data science (NumPy, pandas), machine learning (PyTorch, scikit-learn) and automation. It is also one of the easiest languages to start DSA with.

1. Introduction & Installation

Python code is executed by the Python interpreter line by line — there is no separate compile step for you to run. Files end with .py.

Install

  • Windows: download from python.org/downloads and tick "Add python.exe to PATH" in the installer.
  • macOS: brew install python (or the python.org installer).
  • Linux: usually pre-installed; otherwise sudo apt install python3 python3-pip.

Check the installation and run your first program:

python --version        # python3 --version on macOS/Linux
python hello.py
# hello.py
print("Hello, Codify!")

Output:

Hello, Codify!

You can also open the interactive shell (REPL) by typing python and try code line by line. Install packages with pip install package-name.

⚠️ Common error: 'python' is not recognized as an internal or external command — Python is not on your PATH. Re-run the installer and tick "Add to PATH", or use py on Windows.

2. Basic Syntax

  • Indentation defines blocks (4 spaces is the standard) — there are no { } braces.
  • Statements end at the line break; no semicolons needed.
  • Comments start with #; multi-line notes are often written as """docstrings""".
  • Python is case-sensitive (name and Name are different).
# Read two numbers and print their sum
a = int(input("First: "))
b = int(input("Second: "))
if a + b > 10:
    print("Big sum:", a + b)
else:
    print("Small sum:", a + b)

Output (input 7 and 5):

First: 7
Second: 5
Big sum: 12

⚠️ Common error: IndentationError: expected an indented block — every line inside if, for, def and class must be indented the same amount. Don't mix tabs and spaces.

Practice: Read a name and print Hello, <name>!.

3. Variables & Data Types

Variables are created when you assign them — no type declaration needed (dynamic typing). The type belongs to the value.

Type Example Notes
int 42, -7 unlimited size (no overflow)
float 3.14, 1e-9 double precision
str "hi", 'hi' immutable text
bool True, False capitalised
NoneType None "no value"
list, tuple, dict, set [1,2], (1,2), {"a":1}, {1,2} collections
age = 20
price = 99.5
name = "Asha"
is_student = True
print(type(age), type(price), type(name), type(is_student))
print(int("15") + 5, str(10) + "0", float("2.5") * 2)
big = 2 ** 100          # Python ints never overflow
print(big)

Output:

<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
20 100 5.0
1267650600228229401496703205376

f-strings are the easiest way to format output:

name, score = "Ravi", 92.456
print(f"{name} scored {score:.2f}%")
Ravi scored 92.46%

⚠️ Common error: TypeError: can only concatenate str (not "int") to str — convert first: "Age: " + str(age) or use an f-string.

Practice: Read the radius of a circle and print its area rounded to 2 decimals.

4. Operators

Category Operators
Arithmetic + - * / (true division) // (floor division) % (modulo) ** (power)
Comparison == != < > <= >= (can be chained: 1 < x < 10)
Logical and or not
Assignment = += -= *= /= //= %= **=
Membership in, not in
Identity is, is not (same object, e.g. x is None)
Bitwise `&
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10)
print(-7 // 2, -7 % 2)          # floor division rounds down
x = 5
print(1 < x < 10, x in [1, 5, 9], not x == 5)
print(6 & 3, 6 | 3, 6 ^ 3, 1 << 4)

Output:

3.5 3 1 1024
-4 1
True True False
2 7 5 16

⚠️ Common error: using / when you need an integer index — arr[len(arr)/2] fails with TypeError: list indices must be integers. Use //.

Practice: Check whether a number is even using %, and whether it is a power of two using n & (n - 1) == 0.

5. Conditional Statements

marks = 78
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 50:
    grade = "C"
else:
    grade = "F"
print("Grade:", grade)

# one-line conditional expression (ternary)
status = "pass" if marks >= 50 else "fail"
print(status)

# match-case (Python 3.10+)
command = "stop"
match command:
    case "start":
        print("Starting")
    case "stop" | "quit":
        print("Stopping")
    case _:
        print("Unknown")

Output:

Grade: B
pass
Stopping

Empty values are falsy: 0, 0.0, "", [], {}, None — so if items: checks "list is not empty".

⚠️ Common error: writing if x = 5: (assignment) instead of if x == 5: — it is a SyntaxError.

Practice: Read a year and print whether it is a leap year (divisible by 4 and not by 100, or divisible by 400).

6. Loops

# for loop over a range: range(start, stop, step) — stop is excluded
for i in range(1, 6):
    print(i, end=" ")
print()

# loop over items with their index
fruits = ["apple", "mango", "kiwi"]
for i, f in enumerate(fruits):
    print(i, f)

# while loop
n = 1234
digits = 0
while n > 0:
    n //= 10
    digits += 1
print("digits:", digits)

# break / continue / else
for x in [3, 7, 10, 15]:
    if x % 2 == 0:
        print("first even:", x)
        break
else:
    print("no even number")   # runs only if the loop did NOT break

Output:

1 2 3 4 5 
0 apple
1 mango
2 kiwi
digits: 4
first even: 10

Loop over two lists together with zip(a, b), and backwards with reversed(...) or range(n - 1, -1, -1).

⚠️ Common error: modifying a list while looping over it (e.g. remove inside for x in lst) skips elements. Loop over a copy lst[:] or build a new list.

Practice: Print the multiplication table of n, and the sum of digits of a number.

7. Functions

def greet(name, greeting="Hello"):        # default parameter
    """Return a greeting message."""
    return f"{greeting}, {name}!"

print(greet("Asha"))
print(greet("Ravi", greeting="Namaste"))  # keyword argument

def total(*nums, **options):              # any number of arguments
    s = sum(nums)
    return round(s, options.get("digits", 0))

print(total(1.25, 2.5, 3, digits=1))

square = lambda x: x * x                  # small anonymous function
print(list(map(square, [1, 2, 3])))

def factorial(n):                         # recursion
    return 1 if n <= 1 else n * factorial(n - 1)
print(factorial(5))

Output:

Hello, Asha!
Namaste, Ravi!
6.8
[1, 4, 9]
120

Functions are objects: you can pass them to other functions, return them, and store them in lists. Variables assigned inside a function are local unless declared global/nonlocal.

⚠️ Common error: mutable default arguments — def add(x, items=[]) shares the same list across calls. Use items=None and create the list inside.

💡 Tip: the default recursion limit is about 1000. For deep recursion use loops, or sys.setrecursionlimit(10**6) carefully.

Practice: Write is_prime(n) and use it to print all primes below 50.

8. Arrays & Data Structures

Python's built-in list works as a dynamic array. Other key structures: tuple (immutable list), dict (hash map), set (unique items), plus collections.deque, Counter, defaultdict and heapq.

nums = [5, 2, 9, 1]
nums.append(7); nums.insert(0, 3); nums.sort()
print(nums, nums[0], nums[-1], nums[1:3], len(nums))

squares = [x * x for x in range(6) if x % 2 == 0]   # list comprehension
print(squares)

grid = [[0] * 3 for _ in range(2)]                   # 2-D list (correct way)
grid[0][1] = 5
print(grid)

point = (3, 4)                                        # tuple (immutable)
x, y = point                                          # unpacking
marks = {"asha": 91, "ravi": 78}                      # dict
marks["neha"] = 85
for name, m in marks.items():
    print(name, m)
print(marks.get("john", 0))

seen = {1, 2, 3}; seen.add(2); seen.add(4)            # set
print(seen, 3 in seen)

from collections import Counter, deque
import heapq
print(Counter("banana").most_common(2))
q = deque([1, 2]); q.appendleft(0); q.append(3); print(q.popleft(), list(q))
h = [5, 1, 8]; heapq.heapify(h); heapq.heappush(h, 0); print(heapq.heappop(h), h[0])

Output:

[1, 2, 3, 5, 7, 9] 1 9 [2, 3] 6
[0, 4, 16]
[[0, 5, 0], [0, 0, 0]]
asha 91
ravi 78
neha 85
0
{1, 2, 3, 4} True
[('a', 3), ('n', 2)]
0 [1, 2, 3]
0 1
Operation list dict / set
access / lookup O(1) by index O(1) average by key
append / add O(1) amortised O(1) average
x in O(n) O(1) average
insert / delete at front O(n) — (use deque for queues)

⚠️ Common error: grid = [[0] * 3] * 2 creates two references to the same inner list — changing one row changes both. Use a comprehension.

Practice: Count the frequency of each word in a sentence using a dict (or Counter).

9. Object-Oriented Programming

class Account:
    bank = "Codify Bank"                      # class attribute (shared)

    def __init__(self, owner, balance=0):     # constructor
        self.owner = owner
        self._balance = balance               # "_" = internal by convention

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self._balance += amount

    @property
    def balance(self):                        # read-only attribute
        return self._balance

    def __str__(self):                        # used by print()
        return f"{self.owner}: Rs.{self._balance}"

class Savings(Account):                       # inheritance
    def __init__(self, owner, balance=0, rate=0.04):
        super().__init__(owner, balance)
        self.rate = rate

    def add_interest(self):
        self.deposit(self._balance * self.rate)

acc = Savings("Asha", 1000)
acc.deposit(500)
acc.add_interest()
print(acc, acc.balance, Account.bank, isinstance(acc, Account))

Output:

Asha: Rs.1560.0 1560.0 Codify Bank True

The four pillars: encapsulation (data + methods together, _private by convention), inheritance (class B(A)), polymorphism (same method name, different behaviour; duck typing) and abstraction (abc.ABC and @abstractmethod). Use @dataclass for simple data classes.

⚠️ Common error: forgetting self — def deposit(amount) raises TypeError: deposit() takes 1 positional argument but 2 were given.

Practice: Create a Shape base class with area(), and Rectangle and Circle subclasses; print the areas of a list of shapes.

10. Advanced Concepts

Exceptions

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("cannot divide by zero")
        return None
    finally:
        print("done")

print(safe_divide(10, 2))
print(safe_divide(1, 0))
done
5.0
cannot divide by zero
done
None

File handling — with closes the file automatically:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("line 1\nline 2\n")
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
line 1
line 2

Iterators & generators — yield produces values lazily (memory-friendly):

def countdown(n):
    while n > 0:
        yield n
        n -= 1
print(list(countdown(3)), sum(x * x for x in range(4)))
[3, 2, 1] 14

Decorators wrap a function to add behaviour:

import time
from functools import wraps, lru_cache

def timer(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
        return result
    return wrapper

@lru_cache(maxsize=None)        # memoization in one line
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

@timer
def run():
    return fib(80)
print(run())
run took 0.0001s
23416728348467685

(The time printed will vary.) Other topics worth learning next: modules and packages (import, pip, virtual environments with python -m venv .venv), type hints (def f(x: int) -> str), async/await, and libraries like requests, numpy, pandas and flask.

⚠️ Common error: catching everything with a bare except: hides real bugs. Catch specific exceptions (except ValueError as e:).

11. Examples with Output

Example 1 — Reverse words and check a palindrome

s = "Never odd or even"
clean = "".join(ch.lower() for ch in s if ch.isalnum())
print(" ".join(reversed(s.split())))
print("palindrome" if clean == clean[::-1] else "not palindrome")
even or odd Never
palindrome

Example 2 — Two Sum with a dictionary (O(n))

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

print(two_sum([2, 7, 11, 15], 9))
[0, 1]

Example 3 — Binary search

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11], 7), binary_search([1, 3, 5], 4))
3 -1

Example 4 — Fast input for competitive programming

import sys
data = sys.stdin.buffer.read().split()
n = int(data[0])
arr = list(map(int, data[1:1 + n]))
print(max(arr), sum(arr))

For input 5 and 3 9 2 7 4 this prints 9 25.

12. Practice Problems

Solve these on Codify (choose Python in the editor):

  1. Sum of Two Numbers — input/output basics (Easy)
  2. Reverse a String — slicing s[::-1] (Easy)
  3. Check Palindrome — two pointers or slicing (Easy)
  4. Maximum in an Array — loops / max() (Easy)
  5. Fibonacci Number — recursion → memoization (Easy)
  6. Two Sum — dictionary lookup (Easy)
  7. Binary Search — divide the range (Easy)
  8. Valid Parentheses — list as a stack (Medium)
  9. Maximum Subarray Sum — Kadane's algorithm (Medium)
  10. Longest Common Subsequence — 2-D DP (Medium)

More: the full Codify DSA Sheet has 300 problems from basics to dynamic programming.

13. Interview Questions

1. What is the difference between a list and a tuple? Lists are mutable (can change) and use []; tuples are immutable, use (), are slightly faster and can be dictionary keys.

2. How is memory managed in Python? Objects live on a private heap. CPython uses reference counting plus a cyclic garbage collector for reference cycles.

3. What are *args and **kwargs? *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

4. What is the difference between == and is? == compares values; is checks whether both names point to the same object (use is for None).

5. Shallow copy vs deep copy? copy.copy() copies the outer object but shares nested objects; copy.deepcopy() copies everything recursively.

6. What is a decorator? A function that takes a function and returns a new function with added behaviour, applied with @decorator.

7. What are generators and why use them? Functions with yield that produce values one at a time, keeping state between calls — they use very little memory for large sequences.

8. What is the GIL? The Global Interpreter Lock lets only one thread run Python bytecode at a time in CPython, so threads help with I/O-bound work; use multiprocessing for CPU-bound work.

9. What are list comprehensions? A concise way to build lists: [expr for x in iterable if condition]; there are also dict, set and generator comprehensions.

10. How are dictionaries implemented? As hash tables — average O(1) lookup, insert and delete. Since Python 3.7 they keep insertion order.

14. Cheat Sheet & References

Basics

# Print and read input
print("Hello", name, sep=", ", end="\n")
x = int(input())
a, b = map(int, input().split())
nums = list(map(int, input().split()))
# f-strings
print(f"{name} has {score:.2f} points")
# Type conversion
int("42"); float("3.5"); str(10); list("abc")

Strings

s.upper(); s.lower(); s.strip()
s.split(","); ",".join(words)
s.replace("a", "b"); s.find("x"); s.count("a")
s[::-1]
s.startswith("ab"); s.isdigit(); s.isalpha()

Lists

a.append(x); a.extend([1, 2]); a.insert(i, x)
a.pop(); a.pop(i); a.remove(x)
a.sort(); a.sort(reverse=True); sorted(a, key=len)
a.index(x); a.count(x); a.reverse()
[x * 2 for x in a if x > 0]
a[1:4]; a[::-1]; len(a); sum(a); max(a); min(a)

Dict, set, tuple

d = {"a": 1}; d["b"] = 2; d.get("z", 0)
d.keys(); d.values(); d.items()
d.pop("a"); "a" in d
s = set(); s.add(1); s.discard(1); a | b; a & b; a - b
t = (1, 2); x, y = t

Control flow

# if / elif / else
if x > 0: print("pos")
elif x == 0: print("zero")
else: print("neg")
# loops
for i in range(n): pass
for i, v in enumerate(a): pass
for a_item, b_item in zip(a, b): pass
while x > 0: x -= 1

Functions and classes

def f(a, b=2, *args, **kwargs): return a + b
square = lambda x: x * x
class Dog:
    def __init__(self, name): self.name = name
    def speak(self): return f"{self.name} says woof"

Errors and files

try:
    risky()
except ValueError as e:
    print(e)
finally:
    cleanup()
with open("file.txt") as f: text = f.read()

Useful modules

from collections import Counter, defaultdict, deque
import heapq; heapq.heappush(h, x); heapq.heappop(h)
from functools import lru_cache
import math; math.gcd(a, b); math.sqrt(x); math.inf
import bisect; bisect.bisect_left(a, x)

pip and virtual environments

# Run these in the terminal
python -m venv .venv
pip install requests
pip freeze > requirements.txt

Official documentation