Python
Python
CONTENTS
2
Nested if Statements ....................................................................................................................................................... 21
Ternary Conditional Operator .......................................................................................................................................... 21
Using and, or, not in Conditionals .................................................................................................................................... 21
Conditional Expressions with Functions and Lists ............................................................................................................. 22
LOOPS IN PYTHON ......................................................................................................................................................... 22
for Loop ........................................................................................................................................................................ 22
Basic for Loop ........................................................................................................................................................... 23
Using range() with for Loop ........................................................................................................................................ 23
Iterating over a dictionary ........................................................................................................................................... 23
while Loop .................................................................................................................................................................... 23
Basic while Loop ........................................................................................................................................................ 23
break and continue Statements ........................................................................................................................................ 24
break Statement .......................................................................................................................................................... 24
continue Statement ..................................................................................................................................................... 24
Nested Loops ............................................................................................................................................................. 24
Looping with else ....................................................................................................................................................... 24
for Loop with else ....................................................................................................................................................... 25
while Loop with else ................................................................................................................................................... 25
List Comprehensions .................................................................................................................................................. 25
Looping with zip() ...................................................................................................................................................... 25
STRINGS IN PYTHON ..................................................................................................................................................... 26
Creating Strings ............................................................................................................................................................. 26
Accessing Characters and Slicing .................................................................................................................................... 26
String Concatenation and Repetition ................................................................................................................................ 26
String Methods .............................................................................................................................................................. 27
Changing Case ........................................................................................................................................................... 27
Finding and Replacing ................................................................................................................................................ 27
Splitting and Joining ................................................................................................................................................... 27
Stripping Whitespace .................................................................................................................................................. 28
Checking String Properties .......................................................................................................................................... 28
Formatting Strings ...................................................................................................................................................... 28
Multiline Strings......................................................................................................................................................... 28
Escape Sequences ....................................................................................................................................................... 29
Raw Strings ............................................................................................................................................................... 29
String Length ............................................................................................................................................................. 29
DATA STRUCTURE IN PYTHON .................................................................................................................................... 30
list ................................................................................................................................................................................ 30
Creating Lists ............................................................................................................................................................. 30
Accessing Elements .................................................................................................................................................... 30
Modifying Lists .......................................................................................................................................................... 30
Adding Elements ........................................................................................................................................................ 31
Removing Elements .................................................................................................................................................... 31
Concatenation ............................................................................................................................................................ 32
Repetition .................................................................................................................................................................. 32
Membership ............................................................................................................................................................... 32
List Comprehensions .................................................................................................................................................. 32
List Methods .............................................................................................................................................................. 32
Nested Lists ............................................................................................................................................................... 33
List Functions ............................................................................................................................................................ 33
Tuple ............................................................................................................................................................................ 34
Creating Tuples .......................................................................................................................................................... 34
Accessing Tuple Elements ........................................................................................................................................... 34
Tuple Operations ........................................................................................................................................................ 35
Tuple Methods ........................................................................................................................................................... 35
Immutability .............................................................................................................................................................. 36
Nested Tuples ............................................................................................................................................................ 36
Tuple Unpacking ........................................................................................................................................................ 36
Sets ............................................................................................................................................................................... 36
Creating Sets .............................................................................................................................................................. 36
Accessing Elements .................................................................................................................................................... 37
Set Operations ............................................................................................................................................................ 37
Set Methods ............................................................................................................................................................... 38
Set Comprehensions ................................................................................................................................................... 38
Dictionaries ................................................................................................................................................................... 39
Creating Dictionaries .................................................................................................................................................. 39
Accessing Elements .................................................................................................................................................... 39
Modifying Dictionaries ............................................................................................................................................... 39
Dictionary Methods .................................................................................................................................................... 40
Dictionary Comprehensions ........................................................................................................................................ 41
Functions in Python ........................................................................................................................................................... 41
Introduction ................................................................................................................................................................... 41
Defining a Function ........................................................................................................................................................ 41
Function Components ..................................................................................................................................................... 41
Parameters and Arguments .............................................................................................................................................. 42
Return Statement ............................................................................................................................................................ 43
Scope of Variables ......................................................................................................................................................... 44
Lambda Functions .......................................................................................................................................................... 44
Higher-order Functions ................................................................................................................................................... 44
Documentation Strings (Docstrings) ................................................................................................................................ 44
Function Annotations ..................................................................................................................................................... 45
Closures ........................................................................................................................................................................ 45
Decorators ..................................................................................................................................................................... 45
4
File Handling in Python...................................................................................................................................................... 46
File Modes .................................................................................................................................................................... 46
Opening and Closing Files .............................................................................................................................................. 46
Reading Files ................................................................................................................................................................. 47
Writing to Files .............................................................................................................................................................. 47
Appending to Files ......................................................................................................................................................... 48
File Positioning .............................................................................................................................................................. 48
Binary File Handling ...................................................................................................................................................... 48
Working with CSV Files ................................................................................................................................................. 49
Working with JSON Files ............................................................................................................................................... 49
Exception Handling in Python ............................................................................................................................................ 50
What are Exceptions? ..................................................................................................................................................... 50
The Try-Except Block .................................................................................................................................................... 50
Catching Multiple Exceptions ......................................................................................................................................... 51
The Else Clause ............................................................................................................................................................. 51
The Finally Clause ......................................................................................................................................................... 51
Raising Exceptions ......................................................................................................................................................... 52
Custom Exceptions ......................................................................................................................................................... 52
Assertions...................................................................................................................................................................... 53
Object-Oriented Programming (OOP) in Python ................................................................................................................... 54
Classes and Objects ...................................................................................................................................................... 54
Attributes (Instance and Class Variables) ..................................................................................................................... 54
Methods ....................................................................................................................................................................... 55
Constructor (__init__ method)...................................................................................................................................... 55
Encapsulation ............................................................................................................................................................... 56
Inheritance ................................................................................................................................................................... 56
Polymorphism .............................................................................................................................................................. 56
Abstraction................................................................................................................................................................... 57
Method Overriding....................................................................................................................................................... 57
Method Overloading (Not natively supported in Python) .............................................................................................. 58
Advance concepts in Python ............................................................................................................................................... 59
Decorators ..................................................................................................................................................................... 59
Function Decorators.................................................................................................................................................... 59
Class Decorators......................................................................................................................................................... 59
Generators ..................................................................................................................................................................... 60
Generator Functions.................................................................................................................................................... 60
Generator Expressions ................................................................................................................................................ 60
Iterators and Iterables ..................................................................................................................................................... 61
Custom Iterators ......................................................................................................................................................... 61
Closures ........................................................................................................................................................................ 61
Context Managers .......................................................................................................................................................... 62
Using with Statement .................................................................................................................................................. 62
Custom Context Manager ............................................................................................................................................ 62
Metaclasses ................................................................................................................................................................... 63
Creating a Metaclass ................................................................................................................................................... 63
Functional Programming................................................................................................................................................. 63
Higher-Order Functions .............................................................................................................................................. 63
map(), filter(), and reduce() ......................................................................................................................................... 63
Memory Management in Python ...................................................................................................................................... 64
Reference Counting .................................................................................................................................................... 64
Garbage Collection ..................................................................................................................................................... 64
Coroutines ..................................................................................................................................................................... 65
Basics of NumPy in Python ................................................................................................................................................ 65
Introduction to NumPy ................................................................................................................................................... 65
Installation..................................................................................................................................................................... 65
Importing NumPy .......................................................................................................................................................... 65
NumPy Array (ndarray) .................................................................................................................................................. 66
Creating Arrays .............................................................................................................................................................. 66
Array Attributes ............................................................................................................................................................. 66
Array Indexing and Slicing ............................................................................................................................................. 66
Basic Operations ............................................................................................................................................................ 66
Creating Arrays in NumPy.................................................................................................................................................. 67
Introduction ................................................................................................................................................................... 67
Creating Arrays from Lists or Tuples ............................................................................................................................... 67
Using Built-in Functions ................................................................................................................................................. 67
Random Arrays .............................................................................................................................................................. 68
Array from Existing Data ................................................................................................................................................ 68
Common Functions to Specify Data Types ....................................................................................................................... 68
Array Attributes in NumPy ................................................................................................................................................. 69
Introduction ................................................................................................................................................................... 69
Key Attributes ............................................................................................................................................................... 69
Examples....................................................................................................................................................................... 69
Use Cases ...................................................................................................................................................................... 70
Array Indexing and Slicing in NumPy ................................................................................................................................. 70
Introduction ................................................................................................................................................................... 70
Basic Indexing ............................................................................................................................................................... 70
Slicing ........................................................................................................................................................................... 70
Boolean Indexing ........................................................................................................................................................... 71
Fancy Indexing .............................................................................................................................................................. 71
Modifying Elements ....................................................................................................................................................... 71
Accessing Rows and Columns ......................................................................................................................................... 71
Copy vs View ................................................................................................................................................................ 72
6
Array Manipulation in NumPy.......................................................................................................................................... 72
Introduction .................................................................................................................................................................. 72
Reshaping Arrays ........................................................................................................................................................ 72
Flattening Arrays ......................................................................................................................................................... 73
Joining Arrays .............................................................................................................................................................. 73
Splitting Arrays............................................................................................................................................................. 73
Transposing Arrays ..................................................................................................................................................... 73
Adding Dimensions ...................................................................................................................................................... 74
Removing Dimensions ................................................................................................................................................. 74
Mathematical Operations in NumPy................................................................................................................................ 75
Introduction .................................................................................................................................................................. 75
Element-wise Operations ............................................................................................................................................ 75
Aggregate Functions ................................................................................................................................................... 75
Trigonometric Functions .............................................................................................................................................. 75
Exponential and Logarithmic Functions ...................................................................................................................... 76
Rounding Functions ..................................................................................................................................................... 76
Matrix Operations ........................................................................................................................................................ 76
Broadcasting ................................................................................................................................................................ 76
Comparison Operations ............................................................................................................................................... 77
Linear Algebra in NumPy ................................................................................................................................................ 77
Introduction .................................................................................................................................................................. 77
Matrix Multiplication ..................................................................................................................................................... 77
Determinant of a Matrix ............................................................................................................................................... 77
Inverse of a Matrix ....................................................................................................................................................... 77
Eigenvalues and Eigenvectors .................................................................................................................................... 78
Singular Value Decomposition (SVD) ......................................................................................................................... 78
Solving Linear Systems ............................................................................................................................................... 78
Norm of a Vector or Matrix .......................................................................................................................................... 79
Trace of a Matrix .......................................................................................................................................................... 79
Rank of a Matrix .......................................................................................................................................................... 79
Cross Product .............................................................................................................................................................. 79
Dot Product .................................................................................................................................................................. 79
Random Module in NumPy ............................................................................................................................................. 80
Introduction .................................................................................................................................................................. 80
Generating Random Numbers..................................................................................................................................... 80
Random Arrays ............................................................................................................................................................ 80
Random Sampling ....................................................................................................................................................... 80
Generating Random Numbers from Distributions ....................................................................................................... 81
Shuffling and Permutation ........................................................................................................................................... 81
Seeding the Random Generator.................................................................................................................................. 82
Random State .............................................................................................................................................................. 82
Custom Probability Distributions.................................................................................................................................. 82
Random Boolean Array ............................................................................................................................................... 82
Sorting, Searching, and Counting in NumPy .................................................................................................................. 82
Introduction .................................................................................................................................................................. 82
Sorting in NumPy ..................................................................................................................................................... 83
Searching in NumPy ................................................................................................................................................ 83
Counting in NumPy .................................................................................................................................................. 84
Example: Combined Usage ..................................................................................................................................... 85
8
INTRODUCTION TO PYTHON 9
INTRODUCTION TO PYTHON
1. WHAT IS PYTHON?
High-level language: Python is designed to be easy to read and write, abstracting complex programming details.
Interpreted language: Python code is executed line-by-line, which makes debugging easier but may slow down
execution speed.
General-purpose language: Python is versatile and used in web development, data analysis, artificial intelligence,
scientific computing, and more.
Dynamic typing: Variable types are determined at runtime, which adds flexibility but can lead to runtime errors.
Created by Guido van Rossum: Python was conceived in the late 1980s and first released in 1991.
Open-source: Python's source code is freely available and maintained by the Python Software Foundation.
Python 2 vs. Python 3: Python 3, released in 2008, is the current version and includes many improvements over Python
2, which was discontinued in 2020.
VARIABLES IN PYTHON
INTRODUCTION TO VARIABLES
Variables in Python are used to store data values. They are created when you assign a value to a variable. Python is dynamically
typed, which means you don't need to declare the type of a variable; it is determined at runtime.
CREATING VARIABLES
name = "Alice"
9
10
Python
age = 10
isPass = True
MULTIPLE ASSIGNMENT
x, y, z = 1, 2, 3
a=b=c=0
SWAPPING VARIABLES
a, b = b, a
Primitive data types are the most basic data types available within Python. These types are immutable, meaning their values
cannot be changed once they are created.
Integer (int)
10
DATA TYPES IN PYTHON 11
a = 10
b = -5
Float (float)
c = 3.14
d = -0.001
String (str)
Represents sequences of characters, enclosed in single ('), double ("), or triple quotes (''' """).
name = "Alice"
message = 'Hello, World!'
multiline = """This is a
multiline string."""
Boolean (bool)
is_active = True
is_admin = False
result = None
Reference data types, also known as compound data types, are more complex data structures. These types are mutable, meaning
their values can be changed after they are created.
11
12
Python
List (list)
Tuple (tuple)
Dictionary (dict)
Set (set)
my_set = {1, 2, 3, 4, 5}
COMMENTS IN PYTHON
Comments are lines in a code that are not executed by the interpreter. They are used to explain code and make it more readable for
humans.
SINGLE-LINE COMMENTS
Single-line comments start with a hash symbol (#). Anything after the # on that line is ignored by the Python interpreter.
12
OPERATORS IN PYTHON 13
MULTI-LINE COMMENTS
Python does not have a specific syntax for multi-line comments like some other programming languages. Instead, you can use
multiple single-line comments or use multi-line strings. Although multi-line strings are not technically comments, they can be
used in a similar way.
Multi-line strings can be created using triple quotes (''' or """). When they are not assigned to a variable, they can serve as multi-
line comments.
"""
This is a multi-line comment
using triple double quotes.
It can span multiple lines.
"""
print("Hello, World!")
'''
This is another multi-line comment
using triple single quotes.
It can also span multiple lines.
'''
print("Hello, again!")
OPERATORS IN PYTHON
Operators are special symbols that perform operations on variables and values:
13
14
Python
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
** (Exponentiation)
// (Floor Division)
a = 10
b=3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a % b) # 1
print(a ** b) # 1000
print(a // b) # 3
= (Assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
**= (Exponentiation and assign)
//= (Floor division and assign)
&= (Bitwise AND and assign)
|= (Bitwise OR and assign)
^= (Bitwise XOR and assign)
>>= (Bitwise right shift and assign)
<<= (Bitwise left shift and assign)
a = 10
a += 3 # a = a + 3
print(a) # 13
a -= 3 # a = a - 3
print(a) # 10
a *= 3 # a = a * 3
print(a) # 30
a /= 3 # a = a / 3
14
OPERATORS IN PYTHON 15
print(a) # 10.0
a %= 3 # a = a % 3
print(a) # 1.0
a **= 3 # a = a ** 3
print(a) # 1.0
a //= 3 # a = a // 3
print(a) # 0.0
== (Equal)
!= (Not equal)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)
a = 10
b=3
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
print(a <= b) # False
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
15
16
Python
Identity Operators: These operators are used to compare objects to see if they are the same object.
is
is not
a = [1, 2, 3]
b = [1, 2, 3]
c=a
print(a is b) # False (different objects in memory)
print(a is c) # True (same object in memory)
print(a is not b) # True
Membership Operators: These operators are used to test if a sequence is presented in an object.
in
not in
a = [1, 2, 3, 4, 5]
print(3 in a) # True
print(6 not in a) # True
Special Operators:
Ternary (Conditional) Operator: Used to select one of two values based on a condition.
a=5
b = 10
max_value = a if a > b else b
print(max_value) # 10
Input and output (I/O) operations in Python are essential for interacting with the user:
16
TYPE CONVERSION IN PYTHON 17
You can use the input() function to read a string from the user.
print("Hello, World!")
Type casting, also known as type conversion, is the process of converting one data type into another:
INTEGER (INT())
17
18
Python
FLOAT (FLOAT())
STRING (STR())
BOOLEAN (BOOL())
18
TYPE CONVERSION IN PYTHON 19
LIST (LIST())
TUPLE (TUPLE())
SET (SET())
19
20
Python
DICTIONARY ( DICT())
CONDITIONAL STATEMENT S
Conditional statements allow you to execute different blocks of code based on certain conditions:
IF STATEMENT
The if statement is used to test a condition. If the condition is True, the code block under it gets executed.
a = 10
if a > 5:
print("a is greater than 5")
IF-ELSE STATEMENT
a=3
if a > 5:
print("a is greater than 5")
else:
print("a is not greater than 5")
IF-ELIF-ELSE STATEMENT
20
CONDITIONAL STATEMENTS 21
a = 10
if a > 15:
print("a is greater than 15")
elif a > 5:
print("a is greater than 5 but not greater than 15")
else:
print("a is 5 or less")
NESTED IF STATEMENTS
You can nest if statements within other if statements to check multiple conditions.
a = 10
if a > 5:
if a > 7:
print("a is greater than 7")
else:
print("a is greater than 5 but not greater than 7")
else:
print("a is 5 or less")
Python supports a concise way to perform conditional assignments using the ternary operator.
a = 10
b = 20
max_value = a if a > b else b
print(max_value) # 20
You can combine multiple conditions using logical operators like and, or, and not.
a = 10
b=5
21
22
Python
if not a < 5:
print("a is not less than 5")
You can use conditionals inside list comprehensions, functions, and other expressions.
def check_even(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
print(check_even(4)) # Even
print(check_even(7)) # Odd
LOOPS IN PYTHON
Loops are used to execute a block of code repeatedly. The two primary types of loops are for loops and while loops:
FOR LOOP
A for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).
22
LOOPS IN PYTHON 23
The range() function generates a sequence of numbers, which is often used with loops.
# or
for key, value in [Link]():
print(key, value)
WHILE LOOP
23
24
Python
count = 0
while count < 5:
print(count)
count += 1
BREAK STATEMENT
The break statement is used to exit the loop prematurely when a certain condition is met.
for i in range(10):
if i == 5:
break
print(i) # 0 to 4
CONTINUE STATEMENT
The continue statement is used to skip the current iteration and proceed to the next iteration of the loop.
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
NESTED LOOPS
You can place one loop inside another loop (nested loops).
for i in range(3):
for j in range(3):
print("i = ", i, " , j = ", j)
24
LOOPS IN PYTHON 25
An optional else block can be used with loops. The else block is executed when the loop is exhausted (for for loops) or the
condition becomes false (for while loops), but not when the loop is terminated by a break statement.
for i in range(5):
print(i)
else:
print("Loop completed") # This will be executed
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed") # This will be executed
LIST COMPREHENSIONS
You can use the zip() function to loop over multiple sequences at the same time.
25
26
Python
STRINGS IN PYTHON
Strings in Python are sequences of characters, and they are one of the most commonly used data types:
CREATING STRINGS
Strings can be created by enclosing characters in single quotes, double quotes, triple single quotes, or triple double quotes.
# Single quotes
string1 = 'Hello'
# Double quotes
string2 = "World"
You can access individual characters using indexing, and you can slice strings to get substrings.
# Indexing
string = "Hello"
print(string[0]) # H
print(string[-1]) # o
# Slicing
print(string[1:4]) # ell
print(string[:2]) # He
print(string[2:]) # llo
print(string[::2]) # Hlo (step of 2)
print(string[::-1]) # olleH (reversed string)
You can concatenate strings using the + operator and repeat them using the * operator.
26
STRINGS IN PYTHON 27
# Concatenation
greeting = "Hello" + " " + "World"
print(greeting) # Hello World
# Repetition
laugh = "Ha" * 3
print(laugh) # HaHaHa
STRING METHODS
CHANGING CASE
27
28
Python
STRIPPING WHITESPACE
string = "Hello123"
print([Link]()) # False
print([Link]()) # False
print([Link]()) # True
print([Link]()) # False
print([Link]()) # False
print([Link]()) # False
FORMATTING STRINGS
USING % OPERATOR
name = "John"
age = 30
print("Name: %s, Age: %d" % (name, age)) # Name: John, Age: 30
name = "John"
age = 30
print("Name: {}, Age: {}".format(name, age)) # Name: John, Age: 30
print("Name: {1}, Age: {0}".format(age, name)) # Name: John, Age: 30
name = "John"
age = 30
print(f"Name: {name}, Age: {age}") # Name: John, Age: 30
MULTILINE STRINGS
28
STRINGS IN PYTHON 29
multiline_string = """This is
a multiline
string."""
print(multiline_string)
ESCAPE SEQUENCES
# Newline
print("Hello\nWorld")
# Tab
print("Hello\tWorld")
# Backslash
print("Hello\\World")
# Single quote
print('It\'s a string')
# Double quote
print("He said, \"Hello\"")
RAW STRINGS
raw_string = r"C:\Users\Name"
print(raw_string) # C:\Users\Name
STRING LENGTH
string = "Hello"
print(len(string)) # 5
29
30
Python
LIST
Lists in Python are versatile and widely used data structures that allow you to store collections of items:
CREATING LISTS
Lists are created by placing a comma-separated sequence of elements within square brackets [].
ACCESSING ELEMENTS
# Indexing
print(fruits[0]) # apple
print(fruits[-1]) # cherry
# Slicing
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry']
print(fruits[::2]) # ['apple', 'cherry'] (step of 2)
print(fruits[::-1]) # ['cherry', 'banana', 'apple'] (reversed list)
MODIFYING LISTS
You can modify lists by assigning new values to specific indices or slices.
30
DATA STRUCTURE IN PYTHON 31
ADDING ELEMENTS
REMOVING ELEMENTS
31
32
Python
CONCATENATION
REPETITION
repeated = my_list * 3
MEMBERSHIP
if 2 in my_list:
print("2 is in the list")
LIST COMPREHENSIONS
LIST METHODS
numbers = [3, 1, 4, 1, 5, 9]
# Adding elements
32
DATA STRUCTURE IN PYTHON 33
[Link](2)
print(numbers) # [3, 1, 4, 1, 5, 9, 2]
# Counting occurrences
count_of_ones = [Link](1)
print(count_of_ones) # 2
NESTED LISTS
LIST FUNCTIONS
33
34
Python
numbers = [1, 2, 3, 4, 5]
TUPLE
A tuple is an immutable sequence of Python objects. Tuples are similar to lists, but unlike lists, they cannot be modified after
creation. They are often used to group related data together.
CREATING TUPLES
# Empty Tuple
empty_tuple = ()
# Single-Element Tuple
single_element_tuple = (1,)
my_tuple = (1, 2, 3)
34
DATA STRUCTURE IN PYTHON 35
first_element = my_tuple[0] # 1
last_element = my_tuple[-1] # 3
TUPLE OPERATIONS
tuple1 = (1, 2)
tuple2 = (3, 4)
combined_tuple = tuple1 + tuple2 # (1, 2, 3, 4)
length = len(my_tuple) # 3
TUPLE METHODS
my_tuple = (1, 2, 2, 3)
count_of_two = my_tuple.count(2) # 2
index(x): Returns the index of the first occurrence of x in the tuple. Raises a ValueError if x is not found.
index_of_two = my_tuple.index(2) # 1
IMMUT ABILITY
Tuples are immutable, meaning once they are created, their contents cannot be changed. This immutability provides certain
advantages:
NESTED TUPLES
Tuples can contain other tuples, allowing for complex data structures.
TUPLE UNPACKING
a, b, c = (1, 2, 3)
SETS
A set is an unordered collection of unique elements. Sets are mutable, meaning you can add and remove elements after creation,
but they do not allow duplicate values.
CREATING SETS
36
DATA STRUCTURE IN PYTHON 37
# Syntax
my_set = {1, 2, 3}
# Empty Set
# To create an empty set, use set(). Using {} creates an empty dictionary.
empty_set = set()
ACCESSING ELEMENTS
Sets are unordered, so you cannot access elements by index. You can only check for membership or iterate through the set.
if 2 in my_set:
print("2 is in the set")
SET OPERATIONS
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # {1, 2, 3, 4, 5}
Difference: Gets elements present in the first set but not in the second.
Symmetric Difference: Gets elements present in either set but not in both.
37
38
Python
SET METHODS
add(element): Adds an element to the set. If the element already exists, it will not be added again.
my_set.add(4) # {1, 2, 3, 4}
remove(element): Removes an element from the set. Raises a KeyError if the element is not present.
my_set.remove(3) # {1, 2, 4}
discard(element): Removes an element if it exists, but does not raise an error if the element is not present.
pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.
copied_set = my_set.copy()
SET COMPREHENSIONS
38
DATA STRUCTURE IN PYTHON 39
DICTIONARIES
A dictionary is a mutable, unordered collection of key-value pairs. Each key is unique, and it maps to a specific value.
CREATING DICTIONARIES
Syntax
ACCESSING ELEMENTS
Get Value by Key: Access the value associated with a specific key.
Using get() Method: Retrieve value with optional default if key is not found.
age = my_dict.get('age') # 30
height = my_dict.get('height', 'Not Found') # 'Not Found'
MODIFYING DICTIONARIES
39
40
Python
Using del:
del my_dict['city']
my_dict.clear() # {}
DICTIONARY METHODS
40
Functions in Python 41
popitem(): Removes and returns the last inserted key-value pair as a tuple.
update(): Updates the dictionary with key-value pairs from another dictionary or iterable.
copied_dict = my_dict.copy()
FUNCTIONS IN PYTHON
INTRODUCTION
Purpose: Functions help in organizing code, reducing redundancy, and improving readability and maintainability.
DEFINING A FUNCTION
To define a function, use the def keyword followed by the function name and parentheses ():
def function_name(parameters):
# code block
return result
FUNCTION COMPONENTS
41
42
Python
Example
def greet(name):
return f"Hello, {name}!"
Positional Arguments:
Keyword Arguments:
Default Parameters:
42
Functions in Python 43
Variable-length Arguments:
def sum_all(*args):
return sum(args)
def describe_person(**kwargs):
return kwargs
RETURN STATEMENT
Example:
result = multiply(4, 5)
print(result) # Output: 20
def min_max(numbers):
return min(numbers), max(numbers)
43
44
Python
SCOPE OF VARIABLES
Example:
def local_scope_example():
local_var = "I'm local"
return local_var
LAMBDA FUNCTIONS
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
HIGHER-ORDER FUNCTIONS
Example:
44
Functions in Python 45
Example:
Accessing Docstrings:
FUNCTION ANNOTATIONS
Purpose: Provide optional metadata about the function’s parameters and return value.
Example:
CLOSURES
Definition: Functions that return other functions and capture the local state.
Example:
def make_multiplier(factor):
def multiplier(number):
return number * factor
return multiplier
double = make_multiplier(2)
print(double(5)) # Output: 10
DECORATORS
45
46
Python
Example:
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed")
return original_function()
return wrapper_function
@decorator_function
def display():
return "Display function"
File handling is a critical aspect of programming that allows you to read from and write to files on your disk. Python provides a
built-in way to handle files, making it straightforward to manage data stored in files.
FILE MODES
'r' (Read): Opens a file for reading (default mode). Raises an error if the file does not exist.
'w' (Write): Opens a file for writing. Creates the file if it does not exist. Truncates the file if it exists.
'a' (Append): Opens a file for appending at the end of the file without truncating it. Creates the file if it does not exist.
'x' (Exclusive creation): Creates a new file. Raises an error if the file exists.
'b' (Binary mode): Opens a file in binary mode. Used for non-text files (like images).
't' (Text mode): Opens a file in text mode (default mode).
'+' (Update mode): Opens a file for updating (reading and writing).
Opening a File:
Closing a File:
46
File Handling in Python 47
READING FILES
WRITING TO FILES
47
48
Python
APPENDING TO FILES
Appending Data:
FILE POSITIONING
48
File Handling in Python 49
import csv
import csv
import json
49
50
Python
import json
Exception handling is a crucial aspect of programming that helps manage and respond to errors during code execution. Python
provides a robust mechanism to handle exceptions, ensuring that the program can deal with unexpected situations gracefully.
Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
Basic Syntax:
try:
# Code that might raise an exception
except SomeException as e:
# Code that runs if the exception occurs
Example:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
50
Exception Handling in Python 51
try:
result = int('abc')
except ValueError as e:
print(f"Value Error: {e}")
except TypeError as e:
print(f"Type Error: {e}")
try:
result = int('abc')
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")
Usage: The else block runs if no exceptions are raised in the try block.
Example:
try:
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
Usage: The finally block runs regardless of whether an exception occurs or not. It is often used for cleanup actions (e.g., closing
files or releasing resources).
Example:
51
52
Python
try:
file = open('[Link]', 'r')
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
[Link]()
print("File closed.")
RAISING EXCEPTIONS
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
return "Access granted"
try:
check_age(16)
except ValueError as e:
print(e)
CUSTOM EXCEPTIONS
class CustomError(Exception):
pass
def check_value(value):
if value < 0:
raise CustomError("Value cannot be negative.")
52
Exception Handling in Python 53
try:
check_value(-10)
except CustomError as e:
print(e)
class CustomError(Exception):
def __init__(self, message, code):
[Link] = message
[Link] = code
try:
raise CustomError("An error occurred", 500)
except CustomError as e:
print(f"Error: {[Link]} with code {[Link]}")
ASSERTIONS
Using Assertions: Assertions are a debugging aid that tests a condition as a sanity check. If the condition is True, nothing
happens; if False, an AssertionError is raised.
x=5
assert x > 0, "x must be positive"
Example:
try:
result = divide(10, 0)
except AssertionError as e:
print(e)
53
54
Python
Object-Oriented Programming (OOP) is a paradigm that uses objects and classes to structure code in a more modular, reusable,
and organized way. OOP allows for the bundling of related data and behavior within objects.
Class: A blueprint for creating objects (instances). It defines attributes (data) and methods (functions) that objects created from
the class will have.
Object: An instance of a class. It contains data and methods defined in the class.
class Car:
def __init__(self, make, model):
[Link] = make
[Link] = model
def display_info(self):
print(f"Car make: {[Link]}, model: {[Link]}")
Instance Variables: Variables that belong to an object or instance. Each instance of a class can have different values for instance
variables.
Class Variables: Variables that are shared among all instances of a class. They belong to the class itself.
class Car:
wheels = 4 # Class variable
METHODS
The first parameter of any method in a class is self, which refers to the instance of the class.
class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
print(f"{[Link]} is barking!")
my_dog = Dog("Buddy")
my_dog.bark() # Output: Buddy is barking!
The __init__ method is a special method (constructor) that is automatically called when a new object is created. It is typically used
to initialize the object’s attributes.
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
55
56
Python
ENCAPSULATION
Encapsulation is the practice of keeping the data (attributes) within an object safe from outside interference. In Python, this is
done by making attributes private using a double underscore (__), which makes them inaccessible from outside the class.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
account = BankAccount(100)
[Link](50)
print(account.get_balance()) # Output: 150
INHERITANCE
Inheritance allows one class (child class) to inherit the attributes and methods of another class (parent class). This promotes code
reusability.
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound.")
my_dog = Dog("Buddy")
my_dog.speak() # Output: Buddy barks.
POLYMORPHISM
56
Object-Oriented Programming (OOP) in Python 57
Polymorphism allows the same method to be used in different ways depending on the object calling it. This can be achieved by
method overriding in child classes.
class Bird:
def fly(self):
print("Bird is flying.")
class Penguin(Bird):
def fly(self):
print("Penguins can't fly.")
my_bird = Bird()
my_penguin = Penguin()
ABSTRACTION
Abstraction means hiding the implementation details and showing only the functionality to the user. In Python, abstraction can be
achieved using abstract classes and methods (using the abc module).
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
my_dog = Dog()
my_dog.sound() # Output: Bark
METHOD OVERRIDING
57
58
Python
When a child class defines a method with the same name as a method in the parent class, the method in the child class overrides
the one in the parent class.
class Parent:
def greet(self):
print("Hello from Parent.")
class Child(Parent):
def greet(self):
print("Hello from Child.")
child = Child()
[Link]() # Output: Hello from Child.
Python does not support method overloading like other OOP languages (e.g., Java). However, we can achieve a similar effect by
using default arguments or handling variable argument types inside methods.
class Math:
def add(self, a, b, c=0):
return a + b + c
m = Math()
print([Link](2, 3)) # Output: 5
print([Link](2, 3, 4)) # Output: 9
58
Advance concepts in Python 59
DECORATORS
Decorators are a powerful tool in Python that allow you to modify the behavior of functions or classes. They are higher-order
functions that take another function as an argument and extend or alter its behavior.
FUNCTION DECORATORS
def my_decorator(func):
def wrapper():
print("Something before the function.")
func()
print("Something after the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Something before the function.
# Hello!
# Something after the function.
CLASS DECORATORS
def class_decorator(cls):
class Wrapper:
def __init__(self, *args, **kwargs):
[Link] = cls(*args, **kwargs)
59
60
Python
return Wrapper
@class_decorator
class Person:
def __init__(self, name):
[Link] = name
def greet(self):
print(f"Hello, {[Link]}")
p = Person("Alice")
[Link]() # Output: Hello, Alice
GENERATORS
Generators are functions that allow you to iterate through a sequence of values using the yield keyword. Unlike lists, they do not
store the whole sequence in memory but generate values on the fly, making them memory efficient.
GENERATOR FUNCTIONS
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
counter = count_up_to(5)
print(list(counter)) # Output: [1, 2, 3, 4, 5]
GENERATOR EXPRESSIONS
Generator expressions are similar to list comprehensions, but they use parentheses instead of square brackets and create an iterator
instead of a list.
60
Advance concepts in Python 61
print(val)
# Output: 0, 1, 4, 9, 16
An iterator is an object in Python that implements the __iter__() and __next__() methods. Iterables are objects capable of
returning their members one at a time, such as lists, tuples, and strings.
CUSTOM ITERATORS
You can create your own iterator by defining the __iter__() and __next__() methods.
class MyCounter:
def __init__(self, start, end):
[Link] = start
[Link] = end
def __iter__(self):
return self
def __next__(self):
if [Link] > [Link]:
raise StopIteration
else:
[Link] += 1
return [Link] - 1
counter = MyCounter(1, 5)
for num in counter:
print(num) # Output: 1, 2, 3, 4, 5
CLOSURES
A closure is a function object that remembers values in enclosing scopes even if they are not present in memory anymore. It is
often used to retain the state across multiple function calls.
def outer_function(msg):
61
62
Python
def inner_function():
print(msg)
return inner_function
closure = outer_function("Hello")
closure() # Output: Hello
CONTEXT MANAGERS
Context managers are used for resource management (like file handling). The with statement simplifies the use of context
managers and automatically handles setup and teardown (like opening and closing files).
You can create custom context managers by defining the __enter__() and __exit__() methods.
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
with MyContextManager():
print("Inside the context")
# Output:
# Entering the context
# Inside the context
# Exiting the context
62
Advance concepts in Python 63
METACLASSES
Metaclasses are the "classes of classes." They define how classes behave and are used to control the creation and behavior of new
classes.
CREATING A METACLASS
class MyMeta(type):
def __new__(cls, name, bases, dct):
print("Creating class", name)
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass
FUNCTIONAL PROGRAMMING
Python supports several functional programming features like first-class functions, higher-order functions, map(), filter(), and
reduce().
HIGHER-ORDER FUNCTIONS
Functions that take other functions as arguments or return functions as results are called higher-order functions.
def square(x):
return x * x
63
64
Python
reduce(): Applies a function cumulatively to the items in a list (requires functools module).
nums = [1, 2, 3, 4, 5]
Python has an efficient built-in memory management system that includes reference counting and a garbage collector to free up
memory when it is no longer needed.
REFERENCE COUNTING
Objects in Python are automatically deleted when their reference count drops to zero.
x = [1, 2, 3]
y = x # y points to the same object as x
del x # The object still exists because y references it
print(y) # Output: [1, 2, 3]
GARBAGE COLLECTION
Python’s garbage collector can handle cyclic references. You can manually interact with it using the gc module.
64
Basics of NumPy in Python 65
import gc
[Link]() # Triggers garbage collection
COROUTINES
Coroutines are more advanced generators that allow for asynchronous programming. They are created with async def and can be
paused and resumed using await.
import asyncio
[Link](greet())
INTRODUCTION TO NUMP Y
INSTALLATION
IMPORTING NUMPY
import numpy as np
65
66
Python
CREATING ARRAYS
From a list:
ARRAY ATTRIBUTES
print([Link]) # 2
print([Link]) # (2, 3)
print([Link]) # 6
print([Link]) # int64
Slice arrays:
BASIC OPERATIONS
66
Creating Arrays in NumPy 67
Scalar operations:
print(arr1 * 2) # [2, 4, 6]
INTRODUCTION
Arrays in NumPy are created using the array() function or other specialized functions.
Arrays can be one-dimensional, two-dimensional, or multi-dimensional.
import numpy as np
RANDOM ARRAYS
Random Values:
Random Integers:
68
Array Attributes in NumPy 69
INTRODUCTION
NumPy arrays have several attributes that provide useful information about the array's structure, data type, and memory
usage.
KEY ATTRIBUTES
EXAMPLES
import numpy as np
# Create a 2D array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
# Number of dimensions
print("Number of dimensions:", [Link]) # Output: 2
69
70
Python
USE CASES
INTRODUCTION
Indexing and slicing allow you to access and modify elements, rows, columns, or subarrays in a NumPy array.
BASIC INDEXING
import numpy as np
SLICING
70
Array Indexing and Slicing in NumPy 71
BOOLEAN INDEXING
FANCY INDEXING
MODIFYING ELEMENTS
Modify slices:
For 2D arrays:
71
72
Python
COPY VS VIEW
Slicing creates a view (not a copy) of the array. Changes to the slice affect the original array.
slice = arr[1:3]
slice[0] = 100
print(arr) # Original array is updated
independent_copy = arr[1:3].copy()
INTRODUCTION
NumPy provides functions to reshape, join, split, and modify arrays for efficient manipulation.
RESHAPING ARRAYS
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
reshaped = [Link]((2, 3)) # Reshape to 2 rows and 3 columns
print(reshaped)
# Output:
# [[1 2 3]
# [4 5 6]]
72
Array Manipulation in NumPy 73
FLATTENING ARRAYS
JOINING ARRAYS
SPLITTING ARRAYS
TRANSPOSING ARRAYS
73
74
Python
REMOVING DIMENSIONS
Reverse an array:
74
Mathematical Operations in NumPy 75
INTRODUCTION
NumPy provides efficient mathematical operations on arrays, including element-wise operations, aggregate
functions, and linear algebra.
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
AGGREGATE FUNCTIONS
TRIGONOMETRIC FUNCTIONS
75
76
Python
ROUNDING FUNCTIONS
MATRIX OPERATIONS
BROADCASTING
COMPARISON OPERATIONS
INTRODUCTION
NumPy provides a submodule, [Link], for performing linear algebra operations such as matrix
multiplication, determinants, eigenvalues, and more.
MATRIX MULTIPLICATION
import numpy as np
mat1 = [Link]([[1, 2], [3, 4]])
mat2 = [Link]([[5, 6], [7, 8]])
INVERSE OF A MATRIX
77
78
Python
78
Linear Algebra in NumPy 79
TRACE OF A MATRIX
RANK OF A MATRIX
CROSS PRODUCT
DOT PRODUCT
79
80
Python
INTRODUCTION
NumPy provides a random module for generating random numbers and performing random operations.
import numpy as np
print([Link]()) # Example Output: 0.5488135039273248
Random integers:
RANDOM ARRAYS
RANDOM SAMPLING
Normal distribution:
Uniform distribution:
Binomial distribution:
81
82
Python
[Link](42)
print([Link]()) # Output will always be the same
RANDOM STATE
rng = [Link](42)
print([Link](3)) # Example Output: [0.374, 0.950, 0.732]
INTRODUCTION
NumPy provides efficient functions for sorting, searching, and counting operations on arrays.
82
Sorting, Searching, and Counting in NumPy 83
SORTING IN NUMPY
[Link]()
import numpy as np
arr = [Link]([3, 1, 4, 1, 5])
print([Link](arr)) # Output: [1, 1, 3, 4, 5]
[Link]()
IN-PLACE SORTING
[Link]()
print(arr) # Output: [1, 1, 3, 4, 5]
SEARCHING IN NUMPY
[Link]()
83
84
Python
[Link]()
[Link]()
COUNTING IN NUMPY
NP.COUNT_NONZERO()
[Link]()
84
Sorting, Searching, and Counting in NumPy 85
[Link]()
85