PART 1: PYTHON BASICS
1. Introduction to Python
What is Python
History and features
Applications of Python
Python versions
Installing Python
Python IDEs
First Python program
Python keywords
2. Python Syntax and Basics
Comments
Indentation
Print statement
Input function
Variables
Naming rules
3. Data Types
int
float
complex
bool
string
type() function
Type conversion
4. Operators
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bitwise operators
Membership operators
Identity operators
Operator precedence
5. Strings
Creating strings
Indexing
Slicing
String methods
String formatting
Escape characters
6. Lists
Creating lists
Accessing elements
List slicing
List methods
Adding and removing elements
Nested lists
7. Tuples
Creating tuples
Tuple indexing
Tuple slicing
Tuple methods
Packing and unpacking
8. Sets
Creating sets
Set properties
Set methods
Set operations
Frozen sets
9. Dictionaries
Creating dictionaries
Accessing values
Adding and updating items
Removing items
Dictionary methods
Nested dictionaries
10. Type Casting
Implicit type conversion
Explicit type conversion
11. Control Statements
if statement
if else
if elif else
Nested if
12. Looping Statements
while loop
for loop
range() function
Nested loops
13. Loop Control Statements
break
continue
pass
14. Functions
Defining functions
Calling functions
Arguments and parameters
Return statement
Default arguments
Keyword arguments
Variable length arguments
Recursive functions
15. Scope of Variables
Local scope
Global scope
global keyword
nonlocal keyword
16. Lambda Functions
Lambda syntax
Lambda with single argument
Lambda with multiple arguments
Lambda with map, filter, reduce
17. Modules and Packages
Built-in modules
User-defined modules
Import statements
Packages
[Link]
name variable
18. File Handling
File types
File modes
Reading files
Writing files
Appending files
with statement
19. Exception Handling
Errors and exceptions
try block
except block
else block
finally block
Multiple exceptions
PART 2: OBJECT ORIENTED PROGRAMMING
20. OOP Introduction
Class and object
Constructor
Instance variables
Methods
self keyword
21. OOP Concepts
Inheritance
Types of inheritance
Polymorphism
Method overriding
Encapsulation
Abstraction
1. Introduction to Python
What is Python
Python is a high-level programming language
It is easy to read and easy to write
It is used to develop software, websites, data analysis, and AI applications
History and Features
Python was created by Guido van Rossum
First released in 1991
Simple and readable syntax
Interpreted language
Platform independent
Object-oriented and functional support
Large standard library
Applications of Python
Web development
Data science and data analysis
Artificial Intelligence and Machine Learning
Automation and scripting
Desktop applications
Game development
Cybersecurity and networking
Python Versions
Python 1.x (initial versions)
Python 2.x (now discontinued)
Python 3.x (currently used)
Python 3 is recommended for all new programs
Python versions are backward incompatible from Python 2 to 3
Installing Python
Download Python from official Python website
Available for Windows, Linux, and macOS
Installation includes Python interpreter
Check installation using python --version command
Environment variables setup (PATH)
Python IDEs
IDLE (comes with Python)
Visual Studio Code
PyCharm
Jupyter Notebook
Spyder
IDEs help in writing, running, and debugging programs
First Python Program
Writing a simple print statement
print("Hello World")
Program execution using interpreter
Understanding output
Importance of indentation
Python Keywords
Keywords are reserved words
Keywords have predefined meaning
Cannot be used as variable names
Examples: if, else, for, while, break, continue, def, class, return
Python provides a keyword list using keyword module
2. Python Syntax and Basics
Comments
Comments are used to explain Python code
Comments make the program easy to understand
Comments are ignored by the Python interpreter
Python supports single line comments using the hash symbol
Example:
# This program displays a message
print("Hello Python")
Indentation
Indentation means spaces at the beginning of a statement
Python uses indentation to define blocks of code
Indentation is compulsory in Python
Standard indentation is four spaces
Wrong indentation causes an error
Example:
x = 10
if x > 5:
print("x is greater than 5")
Print Statement
print() is a built-in function in Python
It is used to display output on the screen
It can print text, numbers, and variable values
Multiple values can be printed in one statement
Example:
print("Welcome to Python")
print("Sum =", 10 + 20)
Input Function
input() function is used to get input from the user
The input received is always in string format
Type conversion is required for numeric values
It is used in interactive programs
Example:
name = input("Enter your name: ")
print("Hello", name)
Numeric input example:
age = int(input("Enter age: "))
print("Age =", age)
Variables
Variables are used to store data values
No need to declare data types in advance
A variable is created when a value is assigned
Variable values can be changed during execution
Example:
x = 10
print(x)
x = 50
print(x)
Naming Rules
Variable names must start with a letter or underscore
Variable names must not start with a number
Only letters, numbers, and underscore are allowed
Keywords must not be used as variable names
Variable names are case sensitive
Example:
student_name = "Anu"
total_marks = 480
_count = 5
print(student_name)
print(total_marks)
print(_count)
3. Data Types
int
int is used to store whole numbers
It can store positive and negative values
It does not contain decimal points
Example values are 10, -5, 0
Example:
a = 10
b = -5
print(a)
print(b)
float
float is used to store decimal numbers
It can store fractional values
Example values are 10.5, 3.14, -2.7
Example:
x = 10.5
y = 3.14
print(x)
print(y)
complex
complex data type stores complex numbers
It has a real part and an imaginary part
Imaginary part is represented using j
Example:
c = 3 + 4j
print(c)
bool
bool data type stores Boolean values
It has only two values True and False
It is mainly used in conditions and comparisons
Example:
x = 10
y = 20
print(x > y)
print(x < y)
string
string is used to store text data
Strings are enclosed within single or double quotes
Strings are immutable
It supports indexing and slicing
Example:
name = "Python"
print(name)
type() function
type() function is used to find the data type of a variable
It returns the type of the given value
It is useful for debugging and learning
Example:
x = 10
y = 3.14
name = "Python"
print(type(x))
print(type(y))
print(type(name))
Type Conversion
Type conversion is used to change one data type into another
It is also called type casting
Python supports explicit type conversion
Common functions are int(), float(), str()
Example:
a = "10"
b = int(a)
print(b)
print(type(b))
Another example:
x = 5
y = float(x)
print(y)
print(type(y))
4. Operators
Arithmetic Operators
Used to perform basic mathematical operations
Operators: +, -, *, /, //, %, **
+ addition, - subtraction, * multiplication, / division
// floor division (quotient without decimal)
% modulus (remainder)
** exponent (power)
Example:
a = 10
b = 3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponent: 1000
Assignment Operators
Used to assign values to variables
Examples: =, +=, -=, *=, /=, //=, %=, **=
Example:
x = 5
x += 3 # x = x + 3
print("x after += 3:", x)
x *= 2 # x = x * 2
print("x after *= 2:", x)
Output:
x after += 3: 8
x after *= 2: 16
Relational Operators
Used to compare values
Returns True or False
Operators: ==, !=, >, <, >=, <=
Example:
a = 10
b = 20
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)
Output:
a == b: False
a != b: True
a > b: False
a < b: True
a >= b: False
a <= b: True
Logical Operators
Used to combine conditional statements
Operators: and, or, not
Example:
x = 10
y = 5
print(x > 5 and y < 10) # True and True
print(x > 15 or y < 10) # False or True
print(not(x > 5)) # not True
Output:
True
True
False
Bitwise Operators
Operate on bits of numbers
Operators: &, |, ^, ~, <<, >>
Example:
a = 5 # 0101
b = 3 # 0011
print("a & b:", a & b) # AND
print("a | b:", a | b) # OR
print("a ^ b:", a ^ b) # XOR
print("~a:", ~a) # NOT
print("a << 1:", a << 1) # Left shift
print("a >> 1:", a >> 1) # Right shift
Output:
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2
Membership Operators
Test if a value exists in a sequence
Operators: in, not in
Example:
fruits = ["apple", "banana", "mango"]
print("apple in fruits:", "apple" in fruits)
print("grape not in fruits:", "grape" not in fruits)
Output:
apple in fruits: True
grape not in fruits: True
Identity Operators
Test if two variables refer to the same object
Operators: is, is not
Example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print("a is b:", a is b)
print("a is c:", a is c)
print("a is not c:", a is not c)
Output:
a is b: True
a is c: False
a is not c: True
Operator Precedence
Determines the order in which operators are evaluated
Parentheses ()
Exponent **
Multiplication *, Division /, Floor //, Modulus %
Addition +, Subtraction -
Relational operators
Logical operators
Example:
result = 10 + 5 * 2
print(result) # Multiplication done first
result = (10 + 5) * 2
print(result) # Parentheses change the order
Output:
20
30
5. Strings
Creating Strings
Strings are used to store text data
Strings are enclosed in single quotes ' ' or double quotes " "
Triple quotes ''' ''' or """ """ are used for multi-line strings
Example:
str1 = 'Python'
str2 = "Hello"
str3 = '''This is
a multi-line
string'''
print(str1)
print(str2)
print(str3)
Output:
Python
Hello
This is
a multi-line
string
Indexing
Each character in a string has a position called an index
Indexing starts from 0 for the first character
Negative indexing starts from -1 for the last character
Example:
text = "Python"
print("First character:", text[0])
print("Last character:", text[-1])
Output:
First character: P
Last character: n
Slicing
Extract a part of a string using slicing
Syntax: string[start:end] (end is not included)
Can use step: string[start:end:step]
Example:
text = "PythonProgramming"
print("First 6 characters:", text[0:6])
print("From index 6 to end:", text[6:])
print("Every 2nd character:", text[::2])
Output:
First 6 characters: Python
From index 6 to end: Programming
Every 2nd character: PtoPormig
String Methods
Python has many built-in string methods
Examples: upper(), lower(), capitalize(), strip(), replace(), split()
Example:
text = " hello python "
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]("python", "world"))
print([Link]())
Output:
HELLO PYTHON
hello python
Hello python
hello python
hello world
['hello', 'python']
String Formatting
Used to create strings with variables
Methods: + concatenation, format(), f-strings
Example:
name = "Raji"
age = 20
# Using +
print("My name is " + name + " and age is " + str(age))
# Using format()
print("My name is {} and age is {}".format(name, age))
# Using f-string
print(f"My name is {name} and age is {age}")
Output:
My name is Raji and age is 20
My name is Raji and age is 20
My name is Raji and age is 20
Escape Characters
Special characters used in strings
Examples: \n (new line), \t (tab), \\ (backslash), \' (single quote), \" (double quote)
Example:
print("Hello\nPython") # New line
print("Python\tProgramming") # Tab
print("I am using a backslash \\")
print('He said \'Hello\'')
Output:
Hello
Python
Python Programming
I am using a backslash \
He said 'Hello'
6. Lists
Creating Lists
Lists are used to store multiple values in a single variable
Lists can store numbers, strings, or a mix of data types
Lists are enclosed in square brackets [ ]
Example:
numbers = [10, 20, 30, 40]
fruits = ["apple", "banana", "mango"]
mixed = [1, "Python", 3.14]
print(numbers)
print(fruits)
print(mixed)
Output:
[10, 20, 30, 40]
['apple', 'banana', 'mango']
[1, 'Python', 3.14]
Accessing Elements
Each element in a list has an index
Indexing starts from 0
Negative indexing starts from -1 for the last element
Example:
fruits = ["apple", "banana", "mango"]
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
Output:
First fruit: apple
Last fruit: mango
List Slicing
Extract multiple elements using slicing
Syntax: list[start:end] (end not included)
Can also use step: list[start:end:step]
Example:
numbers = [10, 20, 30, 40, 50, 60]
print("First three numbers:", numbers[0:3])
print("From index 2 to end:", numbers[2:])
print("Every second number:", numbers[::2])
Output:
First three numbers: [10, 20, 30]
From index 2 to end: [30, 40, 50, 60]
Every second number: [10, 30, 50]
List Methods
Lists have many built-in methods like: append(), insert(), remove(), pop(), sort(),
reverse()
Example:
numbers = [10, 20, 30]
[Link](40)
print("After append:", numbers)
[Link](1, 15)
print("After insert:", numbers)
[Link](20)
print("After remove:", numbers)
[Link]()
print("After pop:", numbers)
[Link]()
print("After sort:", numbers)
[Link]()
print("After reverse:", numbers)
Output:
After append: [10, 20, 30, 40]
After insert: [10, 15, 20, 30, 40]
After remove: [10, 15, 30, 40]
After pop: [10, 15, 30]
After sort: [10, 15, 30]
After reverse: [30, 15, 10]
Adding and Removing Elements
append() adds element at the end
insert() adds element at specific position
remove() removes by value
pop() removes by index (last element by default)
Example:
fruits = ["apple", "banana"]
[Link]("mango")
print(fruits)
[Link](1, "orange")
print(fruits)
[Link]("banana")
print(fruits)
[Link]()
print(fruits)
Output:
['apple', 'banana', 'mango']
['apple', 'orange', 'banana', 'mango']
['apple', 'orange', 'mango']
['apple', 'orange']
Nested Lists
A list can contain other lists as elements
Nested lists are useful for storing matrices or grouped data
Example:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Matrix:", matrix)
print("Element at row 2, column 3:", matrix[1][2])
Output:
Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Element at row 2, column 3: 6
7. Tuples
Creating Tuples
Tuples are used to store multiple values in a single variable
Tuples are ordered and immutable (cannot change elements)
Tuples are enclosed in parentheses ( )
Example:
numbers = (10, 20, 30)
fruits = ("apple", "banana", "mango")
mixed = (1, "Python", 3.14)
print(numbers)
print(fruits)
print(mixed)
Output:
(10, 20, 30)
('apple', 'banana', 'mango')
(1, 'Python', 3.14)
Tuple Indexing
Each element in a tuple has an index
Indexing starts from 0
Negative indexing starts from -1 for the last element
Example:
fruits = ("apple", "banana", "mango")
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
Output:
First fruit: apple
Last fruit: mango
Tuple Slicing
Extract multiple elements from a tuple using slicing
Syntax: tuple[start:end] (end is not included)
Can also use step: tuple[start:end:step]
Example:
numbers = (10, 20, 30, 40, 50)
print("First three numbers:", numbers[0:3])
print("From index 2 to end:", numbers[2:])
print("Every second number:", numbers[::2])
Output:
First three numbers: (10, 20, 30)
From index 2 to end: (30, 40, 50)
Every second number: (10, 30, 50)
Tuple Methods
Tuples have very few methods because they are immutable
Common methods: count(), index()
Example:
numbers = (10, 20, 30, 10, 10)
print("Count of 10:", [Link](10))
print("Index of 30:", [Link](30))
Output:
Count of 10: 3
Index of 30: 2
Packing and Unpacking
Packing: Storing multiple values in a single tuple
Unpacking: Extracting values from a tuple into separate variables
Example:
# Packing
person = ("Raji", 20, "CS Student")
# Unpacking
name, age, course = person
print(name)
print(age)
print(course)
Output:
Raji
20
CS Student
8. Sets
Creating Sets
Sets are used to store multiple values in a single variable
Sets are unordered and do not allow duplicate elements
Sets are enclosed in curly braces { }
Example:
fruits = {"apple", "banana", "mango"}
numbers = {10, 20, 30, 10}
print(fruits)
print(numbers)
Output:
{'banana', 'apple', 'mango'}
{10, 20, 30}
Note: Sets are unordered, so order may vary and duplicates are removed.
Set Properties
Unordered: elements have no index
No duplicate elements
Mutable: you can add or remove elements
Supports standard data types (numbers, strings, tuples)
Example:
my_set = {1, 2, 3, 2, 3}
print(my_set)
Output:
{1, 2, 3}
Set Methods
Common set methods:
o add() – adds element
o remove() – removes element (error if not found)
o discard() – removes element (no error if not found)
o pop() – removes and returns a random element
o clear() – removes all elements
Example:
numbers = {1, 2, 3}
[Link](4)
print("After add:", numbers)
[Link](2)
print("After remove:", numbers)
[Link](5)
print("After discard:", numbers)
popped = [Link]()
print("Popped element:", popped)
print("After pop:", numbers)
Output (example, pop may vary):
After add: {1, 2, 3, 4}
After remove: {1, 3, 4}
After discard: {1, 3, 4}
Popped element: 1
After pop: {3, 4}
Set Operations
Supports mathematical operations like union, intersection, difference, symmetric
difference
Example:
A = {1, 2, 3}
B = {3, 4, 5}
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference (A-B):", A - B)
print("Symmetric Difference:", A ^ B)
Output:
Union: {1, 2, 3, 4, 5}
Intersection: {3}
Difference (A-B): {1, 2}
Symmetric Difference: {1, 2, 4, 5}
Frozen Sets
Frozen sets are immutable versions of sets
Cannot add or remove elements
Useful for using sets as dictionary keys
Example:
fs = frozenset([1, 2, 3, 3])
print(fs)
# [Link](4) # This will give error
Output:
frozenset({1, 2, 3})
9. Dictionaries
Creating Dictionaries
Dictionaries store data in key-value pairs
Keys must be unique, values can be duplicate
Dictionaries are unordered
Enclosed in curly braces { }
Example:
student = {"name": "Raji", "age": 20, "course": "CS"}
print(student)
Output:
{'name': 'Raji', 'age': 20, 'course': 'CS'}
Accessing Values
Values are accessed using keys
Use dictionary[key] or [Link](key)
Example:
student = {"name": "Raji", "age": 20, "course": "CS"}
print("Name:", student["name"])
print("Age:", [Link]("age"))
Output:
Name: Raji
Age: 20
Adding and Updating Items
Add new items by assigning value to a new key
Update existing items by assigning value to an existing key
Example:
student = {"name": "Raji", "age": 20}
# Adding
student["course"] = "CS"
print("After adding:", student)
# Updating
student["age"] = 21
print("After updating:", student)
Output:
After adding: {'name': 'Raji', 'age': 20, 'course': 'CS'}
After updating: {'name': 'Raji', 'age': 21, 'course': 'CS'}
Removing Items
Remove items using pop(key)
Remove last inserted item using popitem()
Remove all items using clear()
Delete dictionary completely using del
Example:
student = {"name": "Raji", "age": 21, "course": "CS"}
[Link]("age")
print("After pop:", student)
[Link]()
print("After popitem:", student)
[Link]()
print("After clear:", student)
Output:
After pop: {'name': 'Raji', 'course': 'CS'}
After popitem: {'name': 'Raji'}
After clear: {}
Dictionary Methods
Common methods:
o keys() – returns all keys
o values() – returns all values
o items() – returns key-value pairs as tuples
o get(key) – returns value for the key
o update() – updates dictionary with another dictionary
Example:
student = {"name": "Raji", "age": 20, "course": "CS"}
print("Keys:", [Link]())
print("Values:", [Link]())
print("Items:", [Link]())
[Link]({"age": 21, "grade": "A"})
print("After update:", student)
Output:
Keys: dict_keys(['name', 'age', 'course'])
Values: dict_values(['Raji', 20, 'CS'])
Items: dict_items([('name', 'Raji'), ('age', 20), ('course', 'CS')])
After update: {'name': 'Raji', 'age': 21, 'course': 'CS', 'grade': 'A'}
Nested Dictionaries
A dictionary can contain other dictionaries as values
Useful for storing structured data
Example:
students = {
"student1": {"name": "Raji", "age": 20},
"student2": {"name": "Anu", "age": 21}
}
print(students)
print("Student1 Name:", students["student1"]["name"])
Output:
{'student1': {'name': 'Raji', 'age': 20}, 'student2': {'name': 'Anu', 'age':
21}}
Student1 Name: Raji
Python Comprehensions
Definition (Common Points for all types)
Comprehensions are short, concise ways to create new sequences from existing
iterables
Used to replace loops for creating lists, tuples, sets, or dictionaries
Syntax usually: [expression for item in iterable if condition]
Makes code more readable and Pythonic
1. List Comprehension
Creates a new list from an existing iterable
Can include optional condition
Example:
# Create a list of squares from 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares)
# List of even numbers from 1 to 10
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
Output:
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
2. Tuple Comprehension (Using generator expressions)
Tuples are immutable, so we use parentheses and generator expressions
Example of creating a tuple of squares:
Example:
squares = tuple(x**2 for x in range(1, 6))
print(squares)
Output:
(1, 4, 9, 16, 25)
3. Set Comprehension
Creates a set using comprehension
Automatically removes duplicates
Example:
Example:
# Set of squares from 1 to 5
squares_set = {x**2 for x in range(1, 6)}
print(squares_set)
# Set of even numbers from 1 to 10
evens_set = {x for x in range(1, 11) if x % 2 == 0}
print(evens_set)
Output (order may vary because sets are unordered):
{1, 4, 9, 16, 25}
{2, 4, 6, 8, 10}
4. Dictionary Comprehension
Creates dictionaries using comprehension
Syntax: {key_expr: value_expr for item in iterable if condition}
Example:
# Create a dictionary of number and its square
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)
# Dictionary of even numbers only
even_dict = {x: x*2 for x in range(1, 11) if x % 2 == 0}
print(even_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 8, 6: 12, 8: 16, 10: 20}
💡 Notes :
List comprehension → most common
Tuple comprehension → use generator expression ()
Set comprehension → removes duplicates automatically
Dictionary comprehension → use key: value pairs
Comprehensions are more readable than loops
10. Type Casting
Implicit Type Conversion (Type Coercion)
Python automatically converts one data type to another
Happens when different data types are used in an expression
Usually converts smaller type to bigger type
Safe operation, no data loss
Example:
x = 5 # int
y = 3.5 # float
result = x + y # int is converted to float automatically
print(result)
print(type(result))
Output:
8.5
<class 'float'>
Explicit Type Conversion (Type Casting)
Programmer manually converts a value from one type to another
Functions used: int(), float(), str(), complex()
Example 1 – Convert float to int:
x = 7.8
y = int(x)
print(y)
print(type(y))
Output:
7
<class 'int'>
Example 2 – Convert int to float:
a = 10
b = float(a)
print(b)
print(type(b))
Output:
10.0
<class 'float'>
Example 3 – Convert string to int:
s = "25"
num = int(s)
print(num)
print(type(num))
Output:
25
<class 'int'>
Example 4 – Convert int to complex:
x = 5
y = complex(x)
print(y)
print(type(y))
Output:
(5+0j)
<class 'complex'>
💡 Notes
Implicit conversion → automatic, safe
Explicit conversion → done manually by programmer
Always check data type after conversion using type()
11. Control Statements
if Statement
Used to execute a block of code only if a condition is true
Syntax:
if condition:
# block of code
Executes nothing if condition is false
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
if else Statement
Executes one block if condition is true, another if condition is false
Syntax:
if condition:
# block 1
else:
# block 2
Example:
x = 3
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
Output:
x is odd
if elif else Statement
Used to check multiple conditions
Executes the block of the first true condition
Syntax:
if condition1:
# block1
elif condition2:
# block2
else:
# block3
Example:
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
else:
print("Grade C")
Output:
Grade B
Nested if Statement
if statement inside another if
Used when more than one condition needs to be checked
Example:
x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
Output:
x is greater than 5 and y is greater than 15
💡 Notes :
Use if for a single condition
Use if-else for two outcomes
Use if-elif-else for multiple outcomes
Use nested if for dependent conditions
12. Looping Statements
while Loop
Executes a block of code repeatedly while a condition is True
Syntax:
while condition:
# block of code
Must update variable inside loop to avoid infinite loop
Example:
i = 1
while i <= 5:
print("i =", i)
i += 1
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
for Loop
Executes a block of code for each item in a sequence (list, tuple, string, range)
Syntax:
for variable in sequence:
# block of code
Example 1 – Loop through list:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Example 2 – Loop through string:
for char in "Python":
print(char)
Output:
P
y
t
h
o
n
range() Function
Used to generate a sequence of numbers
Syntax: range(stop), range(start, stop), range(start, stop, step)
Example:
for i in range(5):
print(i)
for i in range(1, 6):
print(i)
for i in range(1, 11, 2):
print(i)
Output:
0
1
2
3
4
1
2
3
4
5
1
3
5
7
9
Nested Loops
A loop inside another loop
Inner loop executes completely for each iteration of outer loop
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
💡 Notes :
while loop → use when number of iterations is unknown
for loop → use when sequence is known
range() → generates numbers for loops
nested loops → useful for patterns, tables, matrices
13. Loop Control Statements
break
Used to exit a loop immediately
Stops the loop even if the condition is still True
Can be used in for or while loops
Example:
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
continue
Skips the current iteration and moves to the next
Loop continues with remaining iterations
Can be used in for or while loops
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
pass
A placeholder statement
Does nothing but is syntactically required
Often used as a temporary block of code
Example:
for i in range(1, 6):
if i == 3:
pass
print(i)
Output:
1
2
3
4
5
💡 Notes :
break → exit loop completely
continue → skip current iteration
pass → placeholder, does nothing
Useful in conditional loops, debugging, and incomplete code
14. Functions
Defining Functions
A function is a block of code that performs a task
Defined using the def keyword
Can be reused multiple times
Example:
def greet():
print("Hello, Raji!")
Calling Functions
Execute a function using its name followed by parentheses
Example:
def greet():
print("Hello, Raji!")
greet()
greet()
Output:
Hello, Raji!
Hello, Raji!
Arguments and Parameters
Parameter → variable defined in function
Argument → value passed to function
Example:
def greet(name):
print("Hello,", name)
greet("Raji")
greet("Anu")
Output:
Hello, Raji
Hello, Anu
Return Statement
Returns a value from a function
Syntax: return value
Example:
def add(a, b):
return a + b
result = add(5, 10)
print("Sum:", result)
Output:
Sum: 15
Default Arguments
Function parameters can have default values
If no argument is passed, default is used
Example:
def greet(name="Student"):
print("Hello,", name)
greet()
greet("Raji")
Output:
Hello, Student
Hello, Raji
Keyword Arguments
Arguments passed by parameter name
Order of arguments does not matter
Example:
def student_info(name, age):
print("Name:", name)
print("Age:", age)
student_info(age=20, name="Raji")
Output:
Name: Raji
Age: 20
Variable Length Arguments
Allows any number of arguments
*args → tuple of positional arguments
**kwargs → dictionary of keyword arguments
Example – *args:
def add_numbers(*args):
print("Sum:", sum(args))
add_numbers(1, 2, 3, 4)
Output:
Sum: 10
Example – **kwargs:
def student_info(**kwargs):
print(kwargs)
student_info(name="Raji", age=20, course="CS")
Output:
{'name': 'Raji', 'age': 20, 'course': 'CS'}
Recursive Functions
A function that calls itself
Must have a base condition to stop recursion
Example – Factorial:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output:
120
💡 Notes :
Functions make code modular and reusable
Arguments allow dynamic input
Return allows value usage outside function
Default, keyword, variable length, recursion → advanced, useful in exams
15. Scope of Variables
Local Scope
Variables defined inside a function
Accessible only inside that function
Cannot be accessed outside the function
Example:
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
# print(x) # Uncommenting this will give error
Output:
Inside function: 10
Global Scope
Variables defined outside any function
Accessible anywhere in the program
Can be used inside functions without passing as parameter
Example:
x = 20 # global variable
def my_function():
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output:
Inside function: 20
Outside function: 20
global Keyword
Used to modify a global variable inside a function
Without global, assignment inside function creates a local variable
Example:
x = 5
def modify():
global x
x = 10
print("Inside function:", x)
modify()
print("Outside function:", x)
Output:
Inside function: 10
Outside function: 10
nonlocal Keyword
Used inside nested functions
Modifies a variable in the nearest outer (non-global) scope
Example:
def outer():
x = 5
def inner():
nonlocal x
x = 10
print("Inside inner:", x)
inner()
print("Inside outer:", x)
outer()
Output:
Inside inner: 10
Inside outer: 10
💡 Notes :
Local → inside function
Global → outside function, accessible everywhere
global keyword → change global variable inside function
nonlocal keyword → change variable in outer enclosing function
Very important for nested functions and scope-related problems
16. Lambda Functions
Lambda Syntax
Lambda functions are anonymous (no name) functions
Can have any number of arguments, but only one expression
Syntax:
lambda arguments: expression
Example:
# Lambda to add 10 to a number
add_10 = lambda x: x + 10
print(add_10(5))
Output:
15
Lambda with Single Argument
Used when a single input is given
Example:
square = lambda x: x**2
print(square(6))
Output:
36
Lambda with Multiple Arguments
Can take two or more inputs
Example:
add = lambda x, y: x + y
print(add(5, 7))
multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4))
Output:
12
24
Lambda with map()
map() applies a function to all items in an iterable
Lambda is useful for inline function
Example:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Output:
[1, 4, 9, 16, 25]
Lambda with filter()
filter() filters items from an iterable based on condition
Example:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output:
[2, 4, 6]
Lambda with reduce()
reduce() applies a function cumulatively to items
reduce() is in functools module
Example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all)
Output:
15
💡 Notes :
Lambda → short, inline functions
Use with map, filter, reduce for functional programming
Saves lines of code and is Pythonic
17. Modules and Packages
Built-in Modules
Python provides pre-written modules that we can use
Examples: math, random, os, datetime
Example:
import math
print("Square root of 16:", [Link](16))
print("Value of pi:", [Link])
Output:
Square root of 16: 4.0
Value of pi: 3.141592653589793
User-defined Modules
We can create our own Python files and use them as modules
Save code in a .py file and import in another file
Example:
[Link]
def greet(name):
return f"Hello, {name}!"
[Link]
import mymodule
print([Link]("Raji"))
Output:
Hello, Raji!
Import Statements
import module_name → imports entire module
from module_name import function_name → imports specific function
import module_name as alias → creates an alias for module
Example:
from math import sqrt
import math as m
print(sqrt(25)) # using from-import
print([Link](5)) # using alias
Output:
5.0
120
Packages
A package is a collection of modules in a folder
Allows organized code structure
Example structure:
mypackage/
__init__.py
[Link]
[Link]
[Link]
Special file used to mark a folder as a package
Can be empty or contain initialization code
Example:
# mypackage/__init__.py
print("Package initialized!")
Output when package imported:
Package initialized!
name Variable
Built-in variable to check if a module is run directly or imported
__name__ == "__main__" → code runs only if the file is executed directly
Example:
def greet():
print("Hello!")
print("This will always print")
if __name__ == "__main__":
print("This runs only if file is executed directly")
Output if run directly:
This will always print
This runs only if file is executed directly
Output if imported:
This will always print
💡 Notes :
Modules → reusable code
Packages → organized collection of modules
import / from / as → different ways to include modules
name → useful in large projects
18. File Handling
File Types
Text files (.txt) → store plain text
Binary files (.bin, .jpg, .pdf) → store non-text data
CSV files (.csv) → store structured tabular data
Python files (.py) → Python code files
File Modes
'r' → Read (default)
'w' → Write (creates file or overwrites)
'a' → Append (adds to the end)
'x' → Create (fails if file exists)
'rb', 'wb', 'ab' → Binary modes
Reading Files
Read file content using read(), readline(), readlines()
Example:
# create a file first
with open("[Link]", "w") as f:
[Link]("Hello Python\nWelcome to file handling\n")
# reading file
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Output:
Hello Python
Welcome to file handling
Writing Files
Write content using write()
Overwrites existing file content
Example:
f = open("[Link]", "w")
[Link]("This is a new content\n")
[Link]()
# read to check
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
This is a new content
Appending Files
Add content without deleting existing data using 'a' mode
Example:
f = open("[Link]", "a")
[Link]("Appending this line\n")
[Link]()
# read to check
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
This is a new content
Appending this line
with Statement
Automatically closes file after block
Preferred way for file handling
Example:
with open("[Link]", "r") as f:
content = [Link]()
print(content)
Output:
This is a new content
Appending this line
💡 Notes
Use with statement → safer and cleaner
Read modes → check data without overwriting
Write mode → overwrite, Append mode → add data
Good for saving, reading, and processing data
19. Exception Handling
Errors and Exceptions
Error → problem in code that stops execution (e.g., syntax error)
Exception → runtime error that can be handled with try-except (e.g., division by zero,
file not found)
Example (Exception):
x = 10
y = 0
# print(x / y) # This would raise ZeroDivisionError
try Block
Code that may raise an exception is written inside try block
Example:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except:
print("An error occurred")
Output (if input is 5):
Enter a number: 5
You entered: 5
except Block
Code executed if an exception occurs in try block
Can catch specific exceptions
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
else Block
Executed if no exception occurs in try block
Example:
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Division successful:", x)
Output:
Division successful: 5.0
finally Block
Executed always, whether exception occurs or not
Used to release resources
Example:
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Execution finished")
Output (if file exists):
This is a new content
Appending this line
Execution finished
Multiple Exceptions
Handle different exceptions in one try block using multiple except statements
Example:
try:
x = int(input("Enter a number: "))
y = 10 / x
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Output (if input = 0):
Enter a number: 0
Cannot divide by zero
Output (if input = 'abc'):
Enter a number: abc
Invalid input
💡 Notes :
Always handle specific exceptions → better practice
finally → use for cleanup (files, connections)
else → optional, runs if no exception
Helps prevent program crash during runtime
20. OOP Introduction
Class and Object
Class → Blueprint for creating objects
Object → Instance of a class
Classes define properties (variables) and behaviors (methods)
Example:
class Student:
pass # empty class
s1 = Student() # creating object
print(s1)
Output:
<__main__.Student object at 0x7f...>
Constructor (__init__ method)
Special method called automatically when object is created
Used to initialize instance variables
Example:
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
s1 = Student("Anu", 20)
print([Link])
print([Link])
Output:
Anu
20
Instance Variables
Variables that belong to the object
Each object has its own copy
Example:
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
s1 = Student("Ravi", 21)
s2 = Student("Meera", 22)
print([Link], [Link])
print([Link], [Link])
Output:
Ravi 21
Meera 22
Methods
Functions defined inside a class
Define behaviors of objects
Example:
class Student:
def __init__(self, name):
[Link] = name
def greet(self):
print("Hello,", [Link])
s1 = Student("Anu")
[Link]()
Output:
Hello, Anu
self Keyword
Refers to the current object
Used to access instance variables and methods
Example:
class Student:
def __init__(self, name):
[Link] = name
def show_name(self):
print("Name is:", [Link])
s1 = Student("Ravi")
s1.show_name()
Output:
Name is: Ravi
💡 Notes :
Class → blueprint
Object → instance of class
Constructor → initializes object
Instance variables → object-specific data
Methods & self → object behaviors and access
21. OOP Concepts
Inheritance
Mechanism to derive a new class (child) from an existing class (parent)
Child class inherits properties and methods of parent class
Helps code reusability and reduces redundancy
Syntax:
class Parent:
# parent class code
class Child(Parent):
# child class code
Example:
class Person:
def __init__(self, name):
[Link] = name
def greet(self):
print("Hello,", [Link])
class Student(Person):
def study(self):
print([Link], "is studying")
s1 = Student("Anu")
[Link]()
[Link]()
Output:
Hello, Anu
Anu is studying
Types of Inheritance
1. Single Inheritance
Child inherits from one parent
Example:
class Parent:
def func1(self):
print("Parent method")
class Child(Parent):
def func2(self):
print("Child method")
c = Child()
c.func1()
c.func2()
Output:
Parent method
Child method
2. Multiple Inheritance
Child inherits from more than one parent
Example:
class Mother:
def mother_func(self):
print("Mother method")
class Father:
def father_func(self):
print("Father method")
class Child(Mother, Father):
def child_func(self):
print("Child method")
c = Child()
c.mother_func()
c.father_func()
c.child_func()
Output:
Mother method
Father method
Child method
3. Multilevel Inheritance
Child inherits from parent, then another child inherits from child
Example:
class Grandparent:
def gp_func(self):
print("Grandparent method")
class Parent(Grandparent):
def p_func(self):
print("Parent method")
class Child(Parent):
def c_func(self):
print("Child method")
c = Child()
c.gp_func()
c.p_func()
c.c_func()
Output:
Grandparent method
Parent method
Child method
4. Hierarchical Inheritance
Multiple children inherit from one parent
Example:
class Parent:
def parent_func(self):
print("Parent method")
class Child1(Parent):
def child1_func(self):
print("Child1 method")
class Child2(Parent):
def child2_func(self):
print("Child2 method")
c1 = Child1()
c2 = Child2()
c1.parent_func()
c1.child1_func()
c2.parent_func()
c2.child2_func()
Output:
Parent method
Child1 method
Parent method
Child2 method
5. Hybrid Inheritance
Combination of two or more types
Example (simple hybrid: single + multiple):
class A:
def funcA(self):
print("Class A")
class B(A):
def funcB(self):
print("Class B")
class C(A):
def funcC(self):
print("Class C")
class D(B, C):
def funcD(self):
print("Class D")
d = D()
[Link]()
[Link]()
[Link]()
[Link]()
Output:
Class A
Class B
Class C
Class D
💡 Notes :
Inheritance → reusability
Single → one parent
Multiple → many parents
Multilevel → chain of inheritance
Hierarchical → one parent, many children
Hybrid → combination
Polymorphism
Definition
Polymorphism means “many forms”
Same operation behaves differently depending on context
Types of Polymorphism
Polymorphism in Python can be mainly classified into three types:
1. Compile-time Polymorphism (Method Overloading / Operator Overloading)
Same method name or operator works differently depending on arguments
Python does not support traditional method overloading, but operator overloading is
possible
Example – Operator Overloading (+ for numbers and strings):
print(5 + 10) # integers → addition
print("Hi " + "There") # strings → concatenation
Output:
15
Hi There
Example – Custom Operator Overloading:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Overloading + operator
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2
print(p3.x, p3.y)
Output:
6 8
2. Run-time Polymorphism (Method Overriding)
Child class overrides parent class method
Behavior determined at runtime
Example:
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
obj = Child()
[Link]()
Output:
Hello from Child
3. Duck Typing / Dynamic Polymorphism
Python is dynamically typed, so same function can work with different types
"If it walks like a duck and quacks like a duck, it’s a duck"
Example:
def add(a, b):
return a + b
print(add(5, 10)) # integers
print(add(2.5, 4.5)) # floats
print(add("Hi ", "There")) # strings
Output:
15
7.0
Hi There
💡 Notes :
Compile-time → operator overloading
Run-time → method overriding
Duck typing → dynamic polymorphism in Python
Polymorphism → makes code flexible, readable, and reusable
Access Specifiers
Definition
Access specifiers define how variables and methods can be accessed
Python does not have strict access control like other languages
Access control is done using naming conventions
Types of Access Specifiers in Python
Public Access Specifier
Members are accessible from anywhere
Default access level in Python
Example:
class Student:
def __init__(self):
[Link] = "Anu"
def display(self):
print([Link])
obj = Student()
[Link]()
print([Link])
Output:
Anu
Anu
Protected Access Specifier (_single underscore)
Members should be accessed within the class and its subclasses
Not enforced, but treated as convention
Example:
class Student:
def __init__(self):
self._age = 20
class Child(Student):
def show(self):
print(self._age)
obj = Child()
[Link]()
Output:
20
Private Access Specifier (__double underscore)
Members are accessible only inside the class
Python uses name mangling for private members
Example:
class Student:
def __init__(self):
self.__marks = 90
def show(self):
print(self.__marks)
obj = Student()
[Link]()
# print(obj.__marks) # This will cause error
Output:
90
💡 Notes :
Public → no underscore
Protected → _variable
Private → __variable
Python enforces access control by convention, not strict rules
Encapsulation
Definition
Encapsulation means binding data and methods together
It hides internal implementation details
Achieved using classes and access specifiers
Example of Encapsulation
class BankAccount:
def __init__(self):
self.__balance = 0 # private variable
def deposit(self, amount):
self.__balance += amount
print("Deposited:", amount)
def show_balance(self):
print("Balance:", self.__balance)
acc = BankAccount()
[Link](1000)
acc.show_balance()
Output:
Deposited: 1000
Balance: 1000
💡 Notes :
Encapsulation = data hiding + data security
Private variables protect data from direct modification
Access data only through methods
Very important concept for real-world applications
Abstraction
Definition
Abstraction means hiding implementation details and showing only essential features
Focuses on what an object does, not how it does
Achieved in Python using abstract classes and abstract methods
Abstract Class
A class that cannot be instantiated (object cannot be created)
Contains one or more abstract methods
Created using the ABC module
Abstract Method
A method declared but not implemented
Child class must implement abstract methods
ABC Module
ABC → Abstract Base Class
@abstractmethod decorator is used
Example of Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def area(self):
return 10 * 5
obj = Rectangle()
print("Area:", [Link]())
Output:
Area: 50
Example Showing Abstract Class Restriction
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# a = Animal() # This will give error
💡 Notes :
Abstraction = design concept
Abstract class → blueprint
Abstract method → compulsory implementation
Improves security, modularity, and maintainability
Frequently asked in theory exams