Python Complete Notes
Python Complete Notes
Table of Contents
Chapter 1 — Introduction to Python
Chapter 2 — Variables, Data Types & Operators
Chapter 3 — Control Flow — if/elif/else, loops
Chapter 4 — Functions
Chapter 5 — Strings
Chapter 6 — Lists
Chapter 7 — Tuples
Chapter 8 — Dictionaries
Chapter 9 — Sets
Chapter 10 — File Handling
Chapter 11 — Modules & Packages
Chapter 12 — Object-Oriented Programming
Chapter 13 — Exception Handling
Chapter 14 — NumPy Basics
Chapter 15 — Comprehensions & Lambda
Chapter 16 — Interview Q&A; Quick Reference
Chapter 1 — Introduction to Python
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in
1991. It emphasizes code readability and simplicity. Python supports multiple programming paradigms:
procedural, object-oriented, and functional programming.
Key Features
• Easy to Learn: Simple English-like syntax.
• Interpreted: Executes line by line — no compilation needed.
• Dynamically Typed: No need to declare variable types.
• Cross-Platform: Runs on Windows, Linux, macOS.
• Huge Standard Library: Built-in modules for almost everything.
• Open Source & Free: Freely available.
• Object-Oriented: Supports classes and objects.
Python Applications
• Web Development (Django, Flask)
• Data Science & Machine Learning (NumPy, Pandas, TensorFlow)
• Automation & Scripting
• Artificial Intelligence
• Game Development (Pygame)
• Desktop Applications
• IoT & Embedded Systems
# Output:
# Hello, World!
# Enter your name: Ravi
# Hello, Ravi
Interview: Q: Why is Python called interpreted? A: Python executes code line-by-line through an interpreter at
runtime, unlike C/C++ which compile the entire code first.
Interview: Q: What is PEP 8? A: PEP 8 is Python's official style guide — it defines coding conventions like
using 4 spaces for indentation, snake_case for variables, etc.
Chapter 2 — Variables, Data Types & Operators
Variables
A variable is a name that refers to a value stored in memory. In Python, variables are created when you assign
a value — no declaration needed.
name = "Priya" # str
age = 21 # int
gpa = 8.5 # float
is_student = True # bool
# Multiple assignment
x = y = z = 0
a, b, c = 1, 2, 3
# Type checking
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
Data Types
Python has the following built-in data types:
# Numeric
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
# Text
s = "Hello" # str
# Boolean
flag = True # bool (True / False)
# None type
val = None # NoneType
# Collections
lst = [1, 2, 3] # list — mutable, ordered
tup = (1, 2, 3) # tuple — immutable, ordered
dct = {"a": 1, "b": 2} # dict — key-value pairs
st = {1, 2, 3} # set — unordered, unique
# Type conversion
print(int("42")) # 42
print(float(10)) # 10.0
print(str(3.14)) # '3.14'
print(bool(0)) # False
print(bool(1)) # True
Operators
Arithmetic Operators
a, b = 15, 4
print(a + b) # 19 Addition
print(a - b) # 11 Subtraction
print(a * b) # 60 Multiplication
print(a / b) # 3.75 Division (always float)
print(a // b) # 3 Floor Division (integer result)
print(a % b) # 3 Modulus (remainder)
print(a ** b) # 50625 Exponentiation (15^4)
# Logical
print(True and False) # False
print(True or False) # True
print(not True) # False
# Identity
x = [1, 2]
y = x
print(x is y) # True (same object)
print(x is [1,2]) # False (different object)
# Membership
lst = [1, 2, 3, 4]
print(3 in lst) # True
print(5 not in lst) # True
Interview: Q: What is the difference between == and is? == compares values; is compares object identity
(memory address). Two lists with same values: == is True, is is False.
Chapter 3 — Control Flow
if / elif / else
Python uses indentation (4 spaces) instead of curly braces to define blocks.
marks = int(input("Enter marks: "))
for Loop
Used to iterate over a sequence (list, tuple, string, range).
# Basic for loop
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
while Loop
n = 1
while n <= 5:
print(n, end=" ")
n += 1
# Output: 1 2 3 4 5
# while-else
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop ended normally")
Tip: Use for loops when you know the number of iterations. Use while loops when the stop condition is dynamic.
Interview: Q: What is the difference between break and continue? break exits the loop entirely; continue skips
the current iteration and moves to the next.
Chapter 4 — Functions
A function is a reusable block of code that performs a specific task. Functions improve modularity and reduce
code repetition.
greet() # call
greet_user("Ravi")
result = add(5, 3)
print(result) # 8
# Keyword arguments
def student_info(name, age, branch):
print(f"{name}, {age}, {branch}")
print(total(1, 2, 3, 4)) # 10
def outer():
x = "Enclosing"
def inner():
x = "Local"
print("Inner:", x) # Local
inner()
print("Outer:", x) # Enclosing
outer()
print("Global:", x) # Global
# global keyword
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Recursive Functions
# Factorial using recursion
def factorial(n):
if n == 0 or n == 1: # base case
return 1
return n * factorial(n - 1) # recursive call
print(factorial(5)) # 120
# Fibonacci
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
Interview: Q: What is recursion? A function that calls itself. Every recursive function needs a base case to stop,
otherwise it causes infinite recursion (RecursionError).
Interview: Q: What are *args and **kwargs? *args collects extra positional arguments as a tuple; **kwargs
collects extra keyword arguments as a dictionary.
Chapter 5 — Strings
A string is a sequence of characters enclosed in single (''), double (""), or triple (''' ''') quotes. Strings are
immutable in Python.
String Operations
s = "Hello, Python!"
# Length
print(len(s)) # 14
# Slicing [start:stop:step]
print(s[0:5]) # Hello
print(s[7:]) # Python!
print(s[:5]) # Hello
print(s[::-1]) # !nohtyP ,olleH (reversed)
# Membership
print("Python" in s) # True
String Methods
s = " Hello, World! "
words = "apple,banana,cherry"
print([Link](",")) # ['apple', 'banana', 'cherry']
print(",".join(["a","b","c"])) # a,b,c
s2 = "Python Programming"
print([Link]("gram")) # 12 (index of first occurrence)
print([Link]("m")) # 2
print([Link]("Py")) # True
print([Link]("ing")) # True
# Check type
print("abc123".isalnum()) # True
print("hello".isalpha()) # True
print("123".isdigit()) # True
print(" ".isspace()) # True
String Formatting
name = "Ravi"
age = 21
gpa = 8.567
# format() method
print("Name: {}, Age: {}".format(name, age))
# Output:
# Name: Ravi, Age: 21, GPA: 8.57
Interview: Q: Are strings mutable in Python? No. Strings are immutable — you cannot change individual
characters. Any operation creates a new string.
Interview: Q: What is the difference between find() and index()? Both find a substring. find() returns -1 if not
found; index() raises ValueError if not found.
Chapter 6 — Lists
A list is an ordered, mutable collection. Elements can be of any data type. Lists use square brackets [].
# Accessing
print(nums[0]) # 1
print(nums[-1]) # 5
print(nums[1:4]) # [2, 3, 4]
print(nested[1][0]) # 3 (row 1, col 0)
# Length
print(len(nums)) # 5
List Methods
lst = [3, 1, 4, 1, 5, 9, 2, 6]
# Membership
print(30 in nums) # True
# Iteration
for n in nums:
print(n, end=" ")
# enumerate
for i, val in enumerate(nums):
print(f"[{i}]={val}", end=" ")
# List comprehension
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Interview: Q: Difference between append() and extend()? append() adds one element; extend() adds all
elements of an iterable to the list.
Interview: Q: Difference between sort() and sorted()? sort() modifies the list in place, returns None. sorted()
returns a new sorted list, original unchanged.
Chapter 7 — Tuples
A tuple is an ordered, immutable collection. Once created, elements cannot be added, removed, or changed.
Tuples use parentheses ().
# Accessing
print(t1[0]) # 1
print(t1[-1]) # 3
print(t1[1:]) # (2, 3)
# Unpacking
a, b, c = t1
print(a, b, c) # 1 2 3
# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
# Tuple methods
t = (3, 1, 4, 1, 5, 9, 2, 6, 1)
print([Link](1)) # 3
print([Link](5)) # 4
# Convert
lst = list(t) # tuple to list
tup = tuple(lst) # list to tuple
Interview: Q: Can a tuple contain mutable objects? Yes. A tuple is immutable (you cannot reassign its
references) but if it contains a list, that list itself can be modified.
Chapter 8 — Dictionaries
A dictionary stores data as key-value pairs. Keys must be unique and immutable. Dictionaries are mutable and
maintain insertion order (Python 3.7+).
# Accessing
print(student["name"]) # Ravi
print([Link]("age")) # 21
print([Link]("city", "N/A")) # N/A (default if missing)
# Modifying
student["age"] = 22 # update
student["branch"] = "CSE" # add new key
# Deleting
del student["gpa"]
popped = [Link]("age") # remove & return
[Link]() # remove last inserted item
Dictionary Methods
d = {"a": 1, "b": 2, "c": 3}
# Iteration
for key, val in [Link]():
print(f" {key} => {val}")
# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
Interview: Q: Can a list be a dictionary key? No. Dictionary keys must be hashable (immutable). Lists are
mutable and unhashable. Use tuples instead.
Chapter 9 — Sets
A set is an unordered collection of unique elements. Useful for removing duplicates and membership testing.
Sets are mutable; frozensets are immutable.
# Creating
s = {1, 2, 3, 4, 5}
s2 = set([1, 2, 2, 3, 3]) # {1, 2, 3} — duplicates removed
empty = set() # NOT {} — that's an empty dict
# Adding / Removing
[Link](6)
[Link](10) # no error if missing
[Link](1) # KeyError if missing
# Set Operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Subset / Superset
print({1,2}.issubset(a)) # True
print([Link]({1,2})) # True
Interview: Q: When would you use a set over a list? When you need uniqueness, fast membership testing (O(1)
vs O(n) for lists), or set operations like union/intersection.
Chapter 10 — File Handling
File handling allows reading from and writing to files. Python's built-in open() function is used with different
modes.
File Modes
# Mode Description
# 'r' Read (default) — error if file not found
# 'w' Write — creates file, overwrites if exists
# 'a' Append — adds to end without overwriting
# 'x' Create — error if file exists
# 'rb' Read binary
# 'wb' Write binary
# 'r+' Read and write
Reading Files
# Method 1: read() — reads entire file
with open("[Link]", "r") as f:
content = [Link]()
print(content)
Writing Files
# Writing
with open("[Link]", "w") as f:
[Link]("Line 1\n")
[Link]("Line 2\n")
# Appending
with open("[Link]", "a") as f:
[Link]("Line 3 (appended)\n")
Binary Files
# Writing binary
data = bytes([72, 101, 108, 108, 111]) # "Hello" in ASCII
with open("[Link]", "wb") as f:
[Link](data)
# Reading binary
with open("[Link]", "rb") as f:
content = [Link]()
print(content) # b'Hello'
print([Link]()) # Hello
Tip: Always use the 'with' statement for file operations. It automatically closes the file even if an exception
occurs.
Interview: Q: What is the difference between read() and readlines()? read() returns the entire content as a
single string. readlines() returns a list of lines.
Chapter 11 — Modules & Packages
A module is a Python file containing functions, classes, and variables that can be reused. A package is a
directory of modules.
Importing Modules
# Variant 1: import module
import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
print([Link](4.7)) # 4
# Alias
import numpy as np
import pandas as pd
Built-in Modules
import random
import time
import os
import sys
# random module
print([Link](1, 10)) # random int 1-10
print([Link]()) # random float 0.0-1.0
print([Link]([1,2,3,4,5])) # random element
lst = [1,2,3,4,5]
[Link](lst) # shuffle in-place
# time module
print([Link]()) # current timestamp (seconds)
print([Link]()) # human-readable time
[Link](1) # pause 1 second
# os module
print([Link]()) # current directory
print([Link]('.')) # list files
[Link]("myfolder", exist_ok=True)
print([Link]("[Link]")) # check if file exists
# math module
import math
print([Link](5)) # 120
print([Link](12, 8)) # 4
print([Link](100, 10)) # 2.0
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
PI = 3.14159
# File: [Link]
import mymath
print([Link](5, 3)) # 8
print([Link]) # 3.14159
print([Link](5)) # 120
Chapter 12 — Object-Oriented Programming (OOP)
OOP is a programming paradigm that organizes code into objects. Python fully supports OOP with the four
pillars: Encapsulation, Inheritance, Polymorphism, and Abstraction.
def greet(self):
print(f"Hi, I'm {[Link]} from {[Link]}")
def grade(self):
if [Link] >= 90: return 'S'
elif [Link] >= 80: return 'A'
elif [Link] >= 70: return 'B'
else: return 'C'
# Creating objects
s1 = Student("Ravi", 20, 85)
s2 = Student("Priya", 21, 92)
Inheritance
Inheritance allows a class (child) to acquire properties and methods of another class (parent). It promotes code
reuse.
class Animal:
def __init__(self, name):
[Link] = name
def eat(self):
print(f"{[Link]} eats food")
def speak(self):
print(f"{[Link]} makes a sound")
class Cat(Animal):
def speak(self):
print(f"{[Link]} says Meow!")
d = Dog("Bruno")
[Link]() # inherited from Animal
[Link]() # overridden — Bruno says Woof!
[Link]() # own method
class Car(Vehicle):
def __init__(self, brand, speed, doors):
super().__init__(brand, speed) # call parent __init__
[Link] = doors
Encapsulation
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # private (name mangled)
self._account_no = "12345" # protected (convention)
Operator Overloading
class Complex:
def __init__(self, r, i):
self.r = r
self.i = i
c1 = Complex(3, 4)
c2 = Complex(1, -2)
print(c1 + c2) # 4+2i
print(c1 - c2) # 2+6i
print(c1 == c2) # False
Interview: Q: What is the difference between __str__ and __repr__? __str__ returns a user-friendly string
(print). __repr__ returns an unambiguous developer string (debugging). If __str__ is missing, Python falls back
to __repr__.
Interview: Q: What is multiple inheritance? A class inheriting from more than one parent class. Python resolves
method lookup using MRO (Method Resolution Order) — C3 linearization algorithm.
Chapter 13 — Exception Handling
An exception is an error that occurs during program execution. Python handles exceptions using try-except
blocks to prevent program crashes.
# TypeError
"5" + 5
# ValueError
int("abc")
# IndexError
[1,2,3][10]
# KeyError
{"a": 1}["b"]
# FileNotFoundError
open("[Link]")
# AttributeError
(5).upper()
# NameError
print(undefined_var)
try:
set_age(-5)
except ValueError as e:
print(e) # Invalid age: -5
class BankAccount:
def __init__(self, balance):
[Link] = balance
try:
acc = BankAccount(500)
[Link](1000)
except InsufficientFundsError as e:
print(e)
Interview: Q: What is the purpose of finally? finally block always executes whether or not an exception
occurred. Used for cleanup — closing files, releasing connections.
Interview: Q: Can we have try without except? Yes, try...finally is valid (no except). But try alone is invalid.
Chapter 14 — NumPy Basics
NumPy (Numerical Python) is the foundation library for scientific computing in Python. It provides fast
multi-dimensional arrays and mathematical operations.
Creating Arrays
import numpy as np
# From list
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([[1,2,3],[4,5,6]]) # 2D
# Special arrays
print([Link]((3,3))) # 3x3 matrix of 0s
print([Link]((2,4))) # 2x4 matrix of 1s
print([Link](3)) # 3x3 identity matrix
print([Link](0, 10, 2)) # [0 2 4 6 8]
print([Link](0, 1, 5)) # [0. 0.25 0.5 0.75 1.]
print([Link](1,10,(3,3))) # 3x3 random ints
# Reshape
b = [Link](1, 13).reshape(3, 4)
# Slicing
print(a[0]) # [1 2 3] — first row
print(a[:, 1]) # [2 5] — second column
print(a[0, 1:]) # [2 3] — row 0, cols 1-end
# Aggregate
print([Link]()) # 21
print([Link]()) # 3.5
print([Link]()) # 6
print([Link]()) # 1
print([Link](axis=0)) # column sums: [5 7 9]
print([Link](axis=1)) # row sums: [6 15]
# One-liner
print(arr[arr > 10]) # [15 22 30]
List Comprehension
A concise way to create lists. Replaces for loops with a single line.
# [expression for item in iterable if condition]
# Squares
squares = [x**2 for x in range(1, 6)]
# [1, 4, 9, 16, 25]
# Even numbers
evens = [x for x in range(1, 21) if x % 2 == 0]
# Flatten a 2D list
flat = [x for row in matrix for x in row]
# Invert a dictionary
d = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in [Link]()}
# {1:'a', 2:'b', 3:'c'}
# Set comprehension
unique_sq = {x**2 for x in [-2,-1,0,1,2]}
# {0, 1, 4}
Lambda Functions
A lambda is an anonymous (nameless) single-expression function. Used for short, throwaway functions.
# lambda arguments: expression
square = lambda x: x**2
add = lambda a, b: a + b
print(square(5)) # 25
print(add(3, 4)) # 7
Interview: Q: When to use lambda vs def? Use lambda for short, one-line anonymous functions passed to
map/filter/sort. Use def for complex, reusable, named functions.
Chapter 16 — Interview Q&A; Quick Reference
Q2. What is the difference between list, tuple, set, and dict?
A: List: ordered, mutable, allows duplicates []. Tuple: ordered, immutable, allows duplicates (). Set: unordered,
mutable, NO duplicates {}. Dict: key-value pairs, mutable, keys unique {}.
Q4. What is the difference between deep copy and shallow copy?
A: Shallow copy ([Link]): copies object but nested objects are still shared. Deep copy ([Link]):
copies everything recursively — completely independent.