0% found this document useful (0 votes)
12 views85 pages

Python

The document serves as a comprehensive introduction to Python, covering its history, key features, and fundamental concepts such as variables, data types, operators, and control structures. It also delves into advanced topics like object-oriented programming, file handling, exception handling, and libraries like NumPy. Overall, it provides a structured guide for both beginners and experienced programmers to understand and utilize Python effectively.

Uploaded by

mehaksoni5948
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views85 pages

Python

The document serves as a comprehensive introduction to Python, covering its history, key features, and fundamental concepts such as variables, data types, operators, and control structures. It also delves into advanced topics like object-oriented programming, file handling, exception handling, and libraries like NumPy. Overall, it provides a structured guide for both beginners and experienced programmers to understand and utilize Python effectively.

Uploaded by

mehaksoni5948
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

CONTENTS

INTRODUCTION TO PYTHON .......................................................................................................................................... 9


1. What is Python? ........................................................................................................................................................... 9
2. History and Development .............................................................................................................................................. 9
3. Key Features of Python ................................................................................................................................................. 9
VARIABLES IN PYTHON .................................................................................................................................................. 9
Introduction to Variables .................................................................................................................................................. 9
Creating Variables ............................................................................................................................................................ 9
Variable Naming Rules ................................................................................................................................................... 10
Multiple Assignment ...................................................................................................................................................... 10
Swapping Variables........................................................................................................................................................ 10
DATA TYPES IN PYTHON .............................................................................................................................................. 10
Primitive Data Types ...................................................................................................................................................... 10
Reference Data Types ..................................................................................................................................................... 11
COMMENTS IN PYTHON ................................................................................................................................................ 12
Single-line Comments .................................................................................................................................................... 12
Multi-line Comments...................................................................................................................................................... 13
Using Multiple Single-line Comments .......................................................................................................................... 13
Using Multi-line Strings .............................................................................................................................................. 13
OPERATORS IN PYTHON ............................................................................................................................................... 13
Arithmetic Operators: These operators are used to perform mathematical operations............................................................ 14
Assignment Operators: These operators are used to assign values to variables. .................................................................... 14
Comparison Operators: These operators compare two values and return a Boolean result. .................................................... 15
Logical Operators: These operators are used to combine conditional statements. ................................................................. 15
INPUT AND OUTPUT IN PYTHON.................................................................................................................................. 16
Taking Input from the User ............................................................................................................................................. 16
Printing Output to the Console ........................................................................................................................................ 17
TYPE CONVERSION IN PYTHON ................................................................................................................................... 17
Integer (int()) ................................................................................................................................................................. 17
Float (float()) ................................................................................................................................................................. 18
String (str()) ................................................................................................................................................................... 18
Boolean (bool())............................................................................................................................................................. 18
List (list()) ..................................................................................................................................................................... 19
Tuple (tuple()) ............................................................................................................................................................... 19
Set (set()) ...................................................................................................................................................................... 19
Dictionary (dict()) .......................................................................................................................................................... 20
CONDITIONAL STATEMENTS ....................................................................................................................................... 20
if Statement ................................................................................................................................................................... 20
if-else Statement ............................................................................................................................................................ 20
if-elif-else Statement ...................................................................................................................................................... 20

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.

2. HISTORY AND DEVELOPMENT

 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.

3. KEY FEATURES OF P YTHON

 Simplicity: Python's syntax is straightforward, making it easier to learn and use.


 Readability: Python code is often said to be as readable as English prose, emphasizing the importance of code
readability.
 Extensive Standard Library: Python comes with a vast library of modules and packages, which provide pre-written
code to perform common tasks.
 Interpreted Language: Python code is executed by an interpreter, which allows for interactive testing and debugging.
 Portability: Python code can run on various platforms without modification (Windows, macOS, Linux, etc.).
 Object-Oriented: Python supports object-oriented programming (OOP) principles, which help in organizing and
managing code complexity.
 Community Support: Python has a large and active community, providing extensive documentation, tutorials, and
third-party modules.

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

Variables are created by assigning a value to a variable name.

name = "Alice"

9
10
Python

age = 10

isPass = True

VARIABLE NAMING RULES

 Variable names must start with a letter or an underscore (_).


 The rest of the variable name can contain letters, numbers, and underscores.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python reserved words (keywords) as variable names (e.g., if, else, while, for, etc.).

MULTIPLE ASSIGNMENT

Python allows you to assign values to multiple variables in a single line.

x, y, z = 1, 2, 3

You can also assign the same value to multiple variables.

a=b=c=0

SWAPPING VARIABLES

You can easily swap the values of two variables in Python.

a, b = b, a

DATA TYPES IN PYTHON

PRIMITIVE DATA TYPES

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)

Represents whole numbers, positive or negative, without decimals.

10
DATA TYPES IN PYTHON 11

a = 10
b = -5

Float (float)

Represents real numbers with a decimal point.

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)

Represents one of two values: True or False.

is_active = True
is_admin = False

None Type (NoneType)

Represents the absence of a value.

result = None

REFERENCE DATA TYPES

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)

Ordered, mutable sequences of elements.

my_list = [1, 2, 3, "four", [5, 6]]

Tuple (tuple)

Ordered, immutable sequences of elements.

my_tuple = (1, 2, 3, "four", (5, 6))

Dictionary (dict)

Unordered collections of key-value pairs.

my_dict = {'name': 'Alice', 'age': 25, 'is_student': True}

Set (set)

Unordered collections of unique elements.

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.

# This is a single-line comment


print("Hello, World!") # This is another single-line comment

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.

USING MULTIPLE SINGLE-LINE COMMENTS

# This is a multi-line comment


# using multiple single-line comments.
# Each line starts with a hash symbol.
print("Hello, World!")

USING MULTI-LINE STRINGS

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

ARITHMETIC OPERATORS: THESE OPERATORS ARE USED TO PERFORM MATHEMATICAL


OPERATIONS.

 + (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 OPERATORS: THESE OPERATORS ARE USED TO ASSIGN VALUES TO VARIABLES.

 = (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

COMPARISON OPERATORS: THESE OPERATORS COMPARE TWO VALUES AND RETURN A


BOOLEAN RESULT.

 == (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

LOGICAL OPERATORS: THESE OPERATORS ARE USED TO COMBINE CONDITIONAL STATEMENTS.

 and (Logical AND)


 or (Logical OR)
 not (Logical NOT)

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 IN PYTHON

Input and output (I/O) operations in Python are essential for interacting with the user:

TAKING INPUT FROM THE USER

16
TYPE CONVERSION IN PYTHON 17

You can use the input() function to read a string from the user.

name = input("Enter your name: ")


print("Hello", name, "!")

PRINTING OUTPUT TO T HE CONSOLE

You can use the print() function to display output.

print("Hello, World!")

# Printing multiple items


print("The answer is", 42)

# Using formatted strings (f-strings)


name = "Alice"
age = 30
print(f"{name} is {age} years old")

# Using the `sep` parameter


print("A", "B", "C", sep="-") # A-B-C

# Using the `end` parameter


print("Hello", end=", ")
print("World!") # Hello, World!

TYPE CONVERSION IN PYTHON

Type casting, also known as type conversion, is the process of converting one data type into another:

INTEGER (INT())

Converts a value to an integer.

# Converting float to integer


x = int(4.7) # 4

# Converting string to integer


y = int("10") # 10

17
18
Python

# Converting boolean to integer


z = int(True) # 1

FLOAT (FLOAT())

Converts a value to a floating-point number.

# Converting integer to float


x = float(5) # 5.0

# Converting string to float


y = float("3.14") # 3.14

# Converting boolean to float


z = float(False) # 0.0

STRING (STR())

Converts a value to a string.

# Converting integer to string


x = str(10) # "10"

# Converting float to string


y = str(3.14) # "3.14"

# Converting boolean to string


z = str(True) # "True"

BOOLEAN (BOOL())

Converts a value to a boolean.

# Converting integer to boolean


x = bool(1) # True
y = bool(0) # False

# Converting float to boolean


z = bool(3.14) # True
w = bool(0.0) # False

18
TYPE CONVERSION IN PYTHON 19

# Converting string to boolean


a = bool("Hello") # True
b = bool("") # False

LIST (LIST())

Converts a value to a list.

# Converting string to list


x = list("Hello") # ['H', 'e', 'l', 'l', 'o']

# Converting tuple to list


y = list((1, 2, 3)) # [1, 2, 3]

# Converting set to list


z = list({1, 2, 3}) # [1, 2, 3]

TUPLE (TUPLE())

Converts a value to a tuple.

# Converting list to tuple


x = tuple([1, 2, 3]) # (1, 2, 3)

# Converting string to tuple


y = tuple("Hello") # ('H', 'e', 'l', 'l', 'o')

# Converting set to tuple


z = tuple({1, 2, 3}) # (1, 2, 3)

SET (SET())

Converts a value to a set.

# Converting list to set


x = set([1, 2, 3, 3, 2]) # {1, 2, 3}

# Converting tuple to set


y = set((1, 2, 2, 3, 4)) # {1, 2, 3, 4}

# Converting string to set

19
20
Python

z = set("Hello") # {'H', 'e', 'l', 'o'}

DICTIONARY ( DICT())

Converts a sequence of key-value pairs to a dictionary.

# Converting list of tuples to dictionary


x = dict([('a', 1), ('b', 2), ('c', 3)]) # {'a': 1, 'b': 2, 'c': 3}

# Converting tuple of tuples to dictionary


y = dict((('a', 1), ('b', 2), ('c', 3))) # {'a': 1, 'b': 2, 'c': 3}

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

The if-else statement provides an alternative action if the condition is False.

a=3
if a > 5:
print("a is greater than 5")
else:
print("a is not greater than 5")

IF-ELIF-ELSE STATEMENT

The if-elif-else statement allows for multiple conditions to be checked sequentially.

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")

TERNARY CONDITIONAL OPERATOR

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

USING AND, OR, NOT IN CONDITIONALS

You can combine multiple conditions using logical operators like and, or, and not.

a = 10
b=5
21
22
Python

if a > 5 and b < 10:


print("Both conditions are True")

if a > 5 or b > 10:


print("At least one condition is True")

if not a < 5:
print("a is not less than 5")

CONDITIONAL EXPRESSIONS WITH FUNCTIONS AND LISTS

You can use conditionals inside list comprehensions, functions, and other expressions.

Example with list comprehension:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # [2, 4, 6, 8, 10]

Example with a function:

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

BASIC FOR LOOP

# Iterating over a list


numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

# Iterating over a string


for char in "Hello":
print(char)

USING RANGE() WITH FOR LOOP

The range() function generates a sequence of numbers, which is often used with loops.

# range(start, stop, step)


for i in range(5):
print(i) # 0 to 4

for i in range(1, 10, 2):


print(i) # 1, 3, 5, 7, 9

ITERATING OVER A DICTIONARY

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}


for key in person:
print(key, person[key])

# or
for key, value in [Link]():
print(key, value)

WHILE LOOP

A while loop is used to execute a block of code as long as a condition is true.

BASIC WHILE LOOP

23
24
Python

count = 0
while count < 5:
print(count)
count += 1

BREAK AND CONTINUE STATEMENTS

These statements are used to alter the flow of loops.

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)

LOOPING WITH ELSE

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 LOOP WITH ELSE

for i in range(5):
print(i)
else:
print("Loop completed") # This will be executed

WHILE LOOP WITH ELSE

count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed") # This will be executed

LIST COMPREHENSIONS

List comprehensions provide a concise way to create lists using loops.

# List of squares of numbers from 0 to 9


squares = [x ** 2 for x in range(10)]
print(squares)

LOOPING WITH ZIP()

You can use the zip() function to loop over multiple sequences at the same time.

names = ['Alice', 'Bob', 'Charlie']


ages = [25, 30, 35]

for name, age in zip(names, ages):


print(name, "is ", age, " years old")

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"

# Triple single quotes (for multiline strings)


string3 = '''This is
a multiline
string'''

# Triple double quotes (for multiline strings)


string4 = """This is also
a multiline
string"""

ACCESSING CHARACTERS AND SLICING

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)

STRING CONCATENATION AND REPETITION

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

Python provides numerous built-in methods for string manipulation.

CHANGING CASE

string = "Hello World"


print([Link]()) # HELLO WORLD
print([Link]()) # hello world
print([Link]()) # Hello World
print([Link]()) # Hello world
print([Link]()) # hELLO wORLD

FINDING AND REPLACING

string = "Hello World"


print([Link]('o')) #4
print([Link]('o')) # 7
print([Link]('o')) # 4
print([Link]('o')) # 7
print([Link]('o')) # 2

print([Link]('World', 'Python')) # Hello Python

SPLITTING AND JOINING

string = "Hello World"


print([Link]()) # ['Hello', 'World']
print([Link]('o')) # ['Hell', ' W', 'rld']

words = ['Hello', 'World']


print(' '.join(words)) # Hello World

27
28
Python

STRIPPING WHITESPACE

string = " Hello World "


print([Link]()) # "Hello World"
print([Link]()) # "Hello World "
print([Link]()) # " Hello World"

CHECKING STRING PROP ERTIES

string = "Hello123"
print([Link]()) # False
print([Link]()) # False
print([Link]()) # True
print([Link]()) # False
print([Link]()) # False
print([Link]()) # False

FORMATTING STRINGS

Python provides several ways to format strings.

USING % OPERATOR

name = "John"
age = 30
print("Name: %s, Age: %d" % (name, age)) # Name: John, Age: 30

USING FORMAT() METHOD

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

USING F-STRINGS (PYTHON 3.6+)

name = "John"
age = 30
print(f"Name: {name}, Age: {age}") # Name: John, Age: 30

MULTILINE STRINGS

28
STRINGS IN PYTHON 29

Use triple quotes for multiline strings.

multiline_string = """This is
a multiline
string."""
print(multiline_string)

ESCAPE SEQUENCES

Escape sequences are used to include special characters in strings.

# 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

Use raw strings to ignore escape sequences.

raw_string = r"C:\Users\Name"
print(raw_string) # C:\Users\Name

STRING LENGTH

Use the len() function to get the length of a string.

string = "Hello"
print(len(string)) # 5

29
30
Python

DATA STRUCTURE IN 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 [].

# Creating an empty list


empty_list = []

# Creating a list with elements


numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", 3.14, True]

ACCESSING ELEMENTS

You can access elements in a list using indexing and slicing.

# 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.

# Changing a single element


fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']

30
DATA STRUCTURE IN PYTHON 31

# Changing multiple elements


fruits[1:3] = ["blackberry", "date"]
print(fruits) # ['apple', 'blackberry', 'date']

ADDING ELEMENTS

You can add elements to a list using append(), extend(), or insert().

# Adding a single element


[Link]("elderberry")
print(fruits) # ['apple', 'blackberry', 'date', 'elderberry']

# Adding multiple elements


[Link](["fig", "grape"])
print(fruits) # ['apple', 'blackberry', 'date', 'elderberry', 'fig', 'grape']

# Inserting an element at a specific position


[Link](1, "banana")
print(fruits) # ['apple', 'banana', 'blackberry', 'date', 'elderberry', 'fig', 'grape']

REMOVING ELEMENTS

You can remove elements using remove(), pop(), or del.

# Removing a specific element


[Link]("date")
print(fruits) # ['apple', 'banana', 'blackberry', 'elderberry', 'fig', 'grape']

# Removing an element by index


removed_element = [Link](2)
print(removed_element) # blackberry
print(fruits) # ['apple', 'banana', 'elderberry', 'fig', 'grape']

# Removing the last element


last_element = [Link]()
print(last_element) # grape
print(fruits) # ['apple', 'banana', 'elderberry', 'fig']

# Deleting an element by index


del fruits[1]
print(fruits) # ['apple', 'elderberry', 'fig']

31
32
Python

CONCATENATION

Combine lists using the + operator.

combined = my_list + [7, 8]

REPETITION

Repeat a list using the * operator.

repeated = my_list * 3

MEMBERSHIP

Check if an item exists in a list.

if 2 in my_list:
print("2 is in the list")

LIST COMPREHENSIONS

List comprehensions provide a concise way to create lists.

# Creating a list of squares


squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]

# Creating a list of even numbers


evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]

LIST METHODS

Python provides various built-in methods for list manipulation.

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

# Finding the index of an element


index_of_four = [Link](4)
print(index_of_four) # 2

# Reversing the list


[Link]()
print(numbers) # [2, 9, 5, 1, 4, 1, 3]

# Sorting the list


[Link]()
print(numbers) # [1, 1, 2, 3, 4, 5, 9]

# Making a shallow copy of the list


numbers_copy = [Link]()
print(numbers_copy) # [1, 1, 2, 3, 4, 5, 9]

# Clearing all elements


[Link]()
print(numbers) # []

NESTED LISTS

Lists can contain other lists as elements, creating nested lists.

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


print(nested_list[0]) # [1, 2, 3]
print(nested_list[0][1]) #2

# Iterating through a nested list


for sublist in nested_list:
for item in sublist:
print(item, end=" ") # 1 2 3 4 5 6 7 8 9

LIST FUNCTIONS

Python provides several built-in functions for working with lists.

33
34
Python

numbers = [1, 2, 3, 4, 5]

# Getting the length of a list


length = len(numbers)
print(length) # 5

# Finding the maximum and minimum values


maximum = max(numbers)
minimum = min(numbers)
print(maximum) # 5
print(minimum) # 1

# Summing all elements


total = sum(numbers)
print(total) # 15

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 = ()

# Creating a tuple with elements


my_tuple = (1, 2, 3)

# Single-Element Tuple
single_element_tuple = (1,)

# Without Parentheses (Tuple Packing)


a = 1, 2, 3 # Equivalent to (1, 2, 3)

ACCESSING TUPLE ELEMENTS

Indexing: Access elements using zero-based indexing.

my_tuple = (1, 2, 3)
34
DATA STRUCTURE IN PYTHON 35

first_element = my_tuple[0] # 1

Negative Indexing: Access elements from the end.

last_element = my_tuple[-1] # 3

Slicing: Obtain a subset of the tuple.

sub_tuple = my_tuple[1:3] # (2, 3)

TUPLE OPERATIONS

Concatenation: Combine tuples using the + operator.

tuple1 = (1, 2)
tuple2 = (3, 4)
combined_tuple = tuple1 + tuple2 # (1, 2, 3, 4)

Repetition: Repeat tuples using the * operator.

repeated_tuple = (1, 2) * 3 # (1, 2, 1, 2, 1, 2)

Membership Test: Check if an item is in a tuple.

contains = 2 in my_tuple # True

Length: Get the number of items in a tuple.

length = len(my_tuple) # 3

TUPLE METHODS

count(x): Returns the number of occurrences of x in the tuple.


35
36
Python

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:

 Hashability: Tuples can be used as keys in dictionaries, while lists cannot.


 Safety: Tuples can be used to ensure that data remains constant and cannot be accidentally modified.

NESTED TUPLES

Tuples can contain other tuples, allowing for complex data structures.

nested_tuple = (1, (2, 3), (4, (5, 6)))

TUPLE UNPACKING

Assign the elements of a tuple to multiple variables.

a, b, c = (1, 2, 3)

Extended Unpacking: Capture remaining elements in a list.

a, *b, c = (1, 2, 3, 4, 5) # a = 1, b = [2, 3, 4], c = 5

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

Union: Combines elements from two or more sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # {1, 2, 3, 4, 5}

Intersection: Gets elements present in both sets.

intersection_set = set1 & set2 # {3}

Difference: Gets elements present in the first set but not in the second.

difference_set = set1 - set2 # {1, 2}

Symmetric Difference: Gets elements present in either set but not in both.

37
38
Python

symmetric_difference_set = set1 ^ set2 # {1, 2, 4, 5}

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.

my_set.discard(5) # {1, 2, 4} (no error if 5 is not in the set)

pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.

element = my_set.pop() # Removes and returns an arbitrary element

clear(): Removes all elements from the set.

my_set.clear() # set() (empty set)

copy(): Returns a shallow copy of the set.

copied_set = my_set.copy()

SET COMPREHENSIONS

Create sets using comprehensions, similar to list comprehensions.

38
DATA STRUCTURE IN PYTHON 39

squares = {x**2 for x in range(6)} # {0, 1, 4, 9, 16, 25}

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

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

Using the dict() Constructor

my_dict = dict(name="Alice", age=30, city="New York")

From a List of Tuples

pairs = [('name', 'Alice'), ('age', 30), ('city', 'New York')]


my_dict = dict(pairs)

ACCESSING ELEMENTS

Get Value by Key: Access the value associated with a specific key.

name = my_dict['name'] # 'Alice'

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

Adding or Updating Key-Value Pairs:

my_dict['email'] = demo@[Link]' # Adds new key-value pair


my_dict['age'] = 31 # Updates existing key

Removing Key-Value Pairs:

Using del:

del my_dict['city']

Using pop(): Removes key and returns its value.

age = my_dict.pop('age') # Removes 'age' and returns 31

Removing All Items:

Using clear(): Empties the dictionary.

my_dict.clear() # {}

DICTIONARY METHODS

keys(): Returns a view object of all the keys.

keys = my_dict.keys() # dict_keys(['name', 'age'])

values(): Returns a view object of all the values.

values = my_dict.values() # dict_values(['Alice', 31])

items(): Returns a view object of all the key-value pairs.

items = my_dict.items() # dict_items([('name', 'Alice'), ('age', 31)])

40
Functions in Python 41

popitem(): Removes and returns the last inserted key-value pair as a tuple.

last_item = my_dict.popitem() # ('age', 31)

update(): Updates the dictionary with key-value pairs from another dictionary or iterable.

my_dict.update({'email': 'alice@[Link]', 'city': 'New York'})

copy(): Returns a shallow copy of the dictionary.

copied_dict = my_dict.copy()

DICTIONARY COMPREHEN SIONS

Create dictionaries using comprehensions, similar to list comprehensions.

square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

FUNCTIONS IN PYTHON

INTRODUCTION

Definition: A function is a reusable block of code that performs a specific task.

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

 Function Name: Identifier for the function.


 Parameters (Optional): Values passed to the function.
 Function Body: Code block executed when the function is called.
 Return Statement (Optional): Sends back a result to the caller.

Example

def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

PARAMETERS AND ARGUMENTS

 Parameters: Variables listed in the function definition.


 Arguments: Values passed to the function when it is called.

Positional Arguments:

def add(a, b):


return a + b

print(add(3, 5)) # Output: 8

Keyword Arguments:

def display_info(name, age):


return f"Name: {name}, Age: {age}"

print(display_info(age=25, name="Bob")) # Output: Name: Bob, Age: 25

Default Parameters:

def power(base, exp=2):


return base ** exp

print(power(3)) # Output: 9 (default exp=2)


print(power(3, 3)) # Output: 27

42
Functions in Python 43

Variable-length Arguments:

*args: Non-keyword arguments.

def sum_all(*args):
return sum(args)

print(sum_all(1, 2, 3, 4)) # Output: 10

**kwargs: Keyword arguments.

def describe_person(**kwargs):
return kwargs

print(describe_person(name="Eve", age=30)) # Output: {'name': 'Eve', 'age': 30}

RETURN STATEMENT

 Purpose: Sends back a value from the function.


 Syntax: return value

Example:

def multiply(x, y):


return x * y

result = multiply(4, 5)
print(result) # Output: 20

Returning Multiple Values: Functions can return multiple values as a tuple.

def min_max(numbers):
return min(numbers), max(numbers)

low, high = min_max([1, 2, 3, 4, 5])


print(low, high) # Output: 1 5

43
44
Python

SCOPE OF VARIABLES

 Local Scope: Variables defined within a function.


 Global Scope: Variables defined outside of all functions.

Example:

def local_scope_example():
local_var = "I'm local"
return local_var

print(local_scope_example()) # Output: I'm local


# print(local_var) # Error: NameError

global_var = "I'm global"


def global_scope_example():
return global_var

print(global_scope_example()) # Output: I'm global

LAMBDA FUNCTIONS

 Definition: Anonymous functions defined using the lambda keyword.


 Syntax: lambda arguments: expression

Example:

square = lambda x: x * x
print(square(5)) # Output: 25

HIGHER-ORDER FUNCTIONS

Functions that take other functions as arguments or return them as results.

Example:

def apply_function(func, value):


return func(value)

print(apply_function(lambda x: x ** 2, 7)) # Output: 49

DOCUMENTATION STRINGS (DOCSTRINGS)

44
Functions in Python 45

 Purpose: Provide a description of the function.


 Syntax: Placed inside triple quotes right after the function definition.

Example:

def add(a, b):


"""
Add two numbers and return the result.
"""
return a + b

Accessing Docstrings:

help(add) # Shows the docstring for the add function

FUNCTION ANNOTATIONS

Purpose: Provide optional metadata about the function’s parameters and return value.

Example:

def greet(name: str, age: int) -> str:


return f"Hello, {name}. You are {age} years old."

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

Definition: Functions that modify the behavior of other functions.

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"

print(display()) # Output: Wrapper executed\nDisplay function

FILE HANDLING IN PYT HON

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 AND CLOSING FILES

Opening a File:

file = open('[Link]', 'r') # Open file in read mode

Closing a File:

[Link]() # Always close the file to free up resources

Using with Statement: Automatically closes the file.

46
File Handling in Python 47

with open('[Link]', 'r') as file:


content = [Link]()

READING FILES

read() Method: Reads the entire content of the file.

with open('[Link]', 'r') as file:


content = [Link]()
print(content)

readline() Method: Reads one line at a time.

with open('[Link]', 'r') as file:


line = [Link]()
while line:
print(line, end='') # Avoid double newline
line = [Link]()

readlines() Method: Reads all lines in a file into a list.

with open('[Link]', 'r') as file:


lines = [Link]()
for line in lines:
print(line, end='')

WRITING TO FILES

write() Method: Writes a string to a file.

with open('[Link]', 'w') as file:


[Link]("Hello, World!")

writelines() Method: Writes a list of strings to a file.

47
48
Python

lines = ["First line\n", "Second line\n", "Third line\n"]


with open('[Link]', 'w') as file:
[Link](lines)

APPENDING TO FILES

Appending Data:

with open('[Link]', 'a') as file:


[Link]("This is an appended line.\n")

FILE POSITIONING

tell() Method: Returns the current position of the file pointer.

with open('[Link]', 'r') as file:


print([Link]()) # Prints the current file pointer position

seek() Method: Changes the file pointer position.

with open('[Link]', 'r') as file:


[Link](0) # Moves the pointer to the beginning of the file
print([Link]())

BINARY FILE HANDLING

Reading Binary Files:

with open('[Link]', 'rb') as file:


content = [Link]()
print(content) # Binary data

Writing Binary Files:

48
File Handling in Python 49

with open('image_copy.png', 'wb') as file:


[Link](content)

WORKING WITH CSV FILES

Reading CSV Files:

import csv

with open('[Link]', 'r') as file:


reader = [Link](file)
for row in reader:
print(row)

Writing CSV Files:

import csv

with open('[Link]', 'w', newline='') as file:


writer = [Link](file)
[Link](['Name', 'Age', 'City'])
[Link](['Alice', 30, 'New York'])

WORKING WITH JSON FI LES

Reading JSON Files:

import json

with open('[Link]', 'r') as file:


data = [Link](file)
print(data)

Writing JSON Files:

49
50
Python

import json

with open('[Link]', 'w') as file:


[Link](data, file)

EXCEPTION HANDLING IN PYTHON

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.

WHAT ARE EXCEPTIONS?

Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Common Exceptions: Some common Python exceptions include:

 ZeroDivisionError: Raised when dividing by zero.


 FileNotFoundError: Raised when a file or directory is requested but doesn’t exist.
 TypeError: Raised when an operation or function is applied to an object of inappropriate type.
 ValueError: Raised when a function receives an argument of the right type but an inappropriate value.
 IndexError: Raised when an index is not found in a sequence (e.g., list).
 KeyError: Raised when a dictionary key is not found.

THE TRY-EXCEPT BLOCK

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

CATCHING MULTIPLE EXCEPTIONS

Handling Different Exceptions Separately:

try:
result = int('abc')
except ValueError as e:
print(f"Value Error: {e}")
except TypeError as e:
print(f"Type Error: {e}")

Handling Multiple Exceptions Together:

try:
result = int('abc')
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")

THE ELSE CLAUSE

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}")

THE FINALLY CLAUSE

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

Manually Raising an Exception:

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)

Raising with Custom Messages:

raise TypeError("This is a custom error message")

CUSTOM EXCEPTIONS

Creating a Custom Exception:

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)

Custom Exception with Arguments:

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:

def divide(a, b):


assert b != 0, "b cannot be zero"
return a / b

try:
result = divide(10, 0)
except AssertionError as e:
print(e)

53
54
Python

OBJECT-ORIENTED PROGRAMMING (OOP) IN 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.

CLASSES AND 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]}")

my_car = Car("Toyota", "Corolla")


my_car.display_info() # Output: Car make: Toyota, model: Corolla

ATTRIBUTES (INSTANCE AND CLASS VARIABLES)

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

def __init__(self, make, model):


54
Object-Oriented Programming (OOP) in Python 55

[Link] = make # Instance variable


[Link] = model # Instance variable

car1 = Car("Toyota", "Camry")


car2 = Car("Honda", "Civic")
print([Link]) # Output: 4
print([Link]) # Output: 4

METHODS

Functions defined inside a class that operate on the object’s data.

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!

CONSTRUCTOR (__INIT__ METHOD)

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

person1 = Person("John", 30)


print([Link]) # Output: John
print([Link]) # Output: 30

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 deposit(self, amount):


self.__balance += amount

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.")

class Dog(Animal): # Inheriting from Animal


def speak(self):
print(f"{[Link]} barks.")

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()

my_bird.fly() # Output: Bird is flying.


my_penguin.fly() # Output: Penguins can't fly.

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).

from abc import ABC, abstractmethod

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.

METHOD OVERLOADING ( NOT NATIVELY SUPPORT ED IN PYTHON)

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

ADVANCE CONCEPTS IN PYTHON

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

A decorator is applied with the @ symbol above the function definition.

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

You can also apply decorators to classes to modify their behavior.

def class_decorator(cls):
class Wrapper:
def __init__(self, *args, **kwargs):
[Link] = cls(*args, **kwargs)

def __getattr__(self, name):


return getattr([Link], name)

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

A function becomes a generator when it contains one or more yield statements.

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.

gen = (x * x for x in range(5))


for val in gen:

60
Advance concepts in Python 61

print(val)
# Output: 0, 1, 4, 9, 16

ITERATORS AND ITERAB LES

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).

USING WITH STATEMENT

with open('[Link]', 'w') as f:


[Link]("Hello, World!")
# The file is automatically closed after the with block

CUSTOM CONTEXT MANAGER

You can create custom context managers by defining the __enter__() and __exit__() methods.

class MyContextManager:
def __enter__(self):
print("Entering the context")
return self

def __exit__(self, exc_type, exc_value, traceback):


print("Exiting the context")

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

You can define a metaclass by inheriting from type.

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

# Output: Creating class MyClass

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

def apply_function(func, value):


return func(value)

print(apply_function(square, 5)) # Output: 25

MAP(), FILTER(), AND REDUCE()

map(): Applies a function to all items in an input list.

63
64
Python

filter(): Filters the input list based on a function's condition.

reduce(): Applies a function cumulatively to the items in a list (requires functools module).

from functools import reduce

nums = [1, 2, 3, 4, 5]

# Map: Squaring each number


squared = list(map(lambda x: x * x, nums))
print(squared) # Output: [1, 4, 9, 16, 25]

# Filter: Only even numbers


evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4]

# Reduce: Summing all numbers


total = reduce(lambda x, y: x + y, nums)
print(total) # Output: 15

MEMORY MANAGEMENT IN PYTHON

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

async def greet():


print("Hello!")
await [Link](1)
print("World!")

[Link](greet())

BASICS OF NUMPY IN P YTHON

INTRODUCTION TO NUMP Y

 NumPy (Numerical Python) is a Python library for numerical computations.


 It provides support for large, multi-dimensional arrays and matrices.
 It offers a collection of mathematical functions to operate on these arrays.

INSTALLATION

 Install NumPy using pip:

pip install numpy

IMPORTING NUMPY

 Import NumPy in your Python script:

import numpy as np

65
66
Python

NUMPY ARRAY (NDARRAY)

 Central to NumPy is the ndarray (n-dimensional array) object.


 Advantages over Python lists:
o Faster execution
o Less memory consumption
o Support for element-wise operations

CREATING ARRAYS

 From a list:

arr = [Link]([1, 2, 3])

ARRAY ATTRIBUTES

 ndim: Number of dimensions


 shape: Tuple of array dimensions
 size: Total number of elements
 dtype: Data type of elements
 itemsize: Size of each element in bytes
 Example:

arr = [Link]([[1, 2, 3], [4, 5, 6]])

print([Link]) # 2
print([Link]) # (2, 3)
print([Link]) # 6
print([Link]) # int64

ARRAY INDEXING AND S LICING

 Access elements using indices:

arr = [Link]([10, 20, 30, 40])


print(arr[2]) # 30

 Slice arrays:

print(arr[1:3]) # [20, 30]

BASIC OPERATIONS

 Element-wise addition, subtraction, multiplication, division:

66
Creating Arrays in NumPy 67

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([4, 5, 6])
print(arr1 + arr2) # [5, 7, 9]

 Scalar operations:

print(arr1 * 2) # [2, 4, 6]

CREATING ARRAYS IN NUMPY

INTRODUCTION

 Arrays in NumPy are created using the array() function or other specialized functions.
 Arrays can be one-dimensional, two-dimensional, or multi-dimensional.

CREATING ARRAYS FROM LISTS OR TUPLES

 Convert Python lists or tuples into NumPy arrays:

import numpy as np

arr1 = [Link]([1, 2, 3]) # 1D array


arr2 = [Link]([[1, 2], [3, 4]]) # 2D array

USING BUILT -IN FUNCTIONS

 Zeros Array: Create an array filled with zeros.

zeros = [Link]((2, 3)) # 2x3 array of zeros

 Ones Array: Create an array filled with ones.

ones = [Link]((3, 3)) # 3x3 array of ones

 Empty Array: Create an uninitialized array (random values).

empty = [Link]((2, 2)) # 2x2 uninitialized array


67
68
Python

 Identity Matrix: Create a square identity matrix.

identity = [Link](3) # 3x3 identity matrix

 Arange: Create an array with a range of values.

arange = [Link](0, 10, 2) # [0, 2, 4, 6, 8]

 Linspace: Create an array with equally spaced values.

linspace = [Link](0, 1, 5) # [0. , 0.25, 0.5, 0.75, 1. ]

RANDOM ARRAYS

 Random Values:

random_array = [Link](2, 3) # 2x3 array of random values

 Random Integers:

random_integers = [Link](0, 10, (3, 3)) # 3x3 array of random integers

ARRAY FROM EXISTING DATA

 Create arrays using existing data:

existing = [Link]([1, 2, 3])


copy = [Link](existing) # Create a copy

COMMON FUNCTIONS TO SPECIFY DATA TYPES

 Specify the data type using the dtype parameter:

68
Array Attributes in NumPy 69

float_array = [Link]([1, 2, 3], dtype=float)

ARRAY ATTRIBUTES IN NUMPY

INTRODUCTION

 NumPy arrays have several attributes that provide useful information about the array's structure, data type, and memory
usage.

KEY ATTRIBUTES

Attribute Description Example


ndim Number of dimensions of the array [Link]
shape Tuple representing the dimensions of the array [Link]
size Total number of elements in the array [Link]
dtype Data type of the elements in the array [Link]
itemsize Size (in bytes) of each element in the array [Link]
nbytes Total memory consumed by the array (in bytes) [Link]

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

# Shape of the array


print("Shape of the array:", [Link]) # Output: (2, 3)

# Total number of elements


print("Total elements:", [Link]) # Output: 6

# Data type of elements


print("Data type:", [Link]) # Output: int64

# Size of each element


print("Item size:", [Link], "bytes") # Output: 8 bytes

# Total memory consumption

69
70
Python

print("Total bytes:", [Link], "bytes") # Output: 48 bytes

USE CASES

 ndim: Useful to determine if the array is 1D, 2D, or multi-dimensional.


 shape: Helpful for reshaping arrays.
 dtype: Ensures the array contains the correct type of data (e.g., float, int).
 nbytes: Helps in memory optimization for large arrays.

ARRAY INDEXING AND S LICING IN NUMPY

INTRODUCTION

 Indexing and slicing allow you to access and modify elements, rows, columns, or subarrays in a NumPy array.

BASIC INDEXING

 Access elements using indices (zero-based indexing):

import numpy as np

arr = [Link]([10, 20, 30, 40])


print(arr[2]) # Output: 30

 For multi-dimensional arrays:

arr2d = [Link]([[1, 2, 3], [4, 5, 6]])


print(arr2d[1, 2]) # Output: 6

SLICING

 Extract a subset of elements using slicing syntax: start:stop:step.

arr = [Link]([10, 20, 30, 40, 50])


print(arr[1:4]) # Output: [20, 30, 40]
print(arr[::2]) # Output: [10, 30, 50]

70
Array Indexing and Slicing in NumPy 71

 For multi-dimensional arrays:

arr2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


print(arr2d[1:, :2]) # Output: [[4, 5], [7, 8]]

BOOLEAN INDEXING

 Access elements that satisfy a condition:

arr = [Link]([10, 15, 20, 25])


print(arr[arr > 15]) # Output: [20, 25]

FANCY INDEXING

 Access specific elements using a list of indices:

arr = [Link]([10, 20, 30, 40])


print(arr[[0, 2]]) # Output: [10, 30]

MODIFYING ELEMENTS

 Modify specific elements:

arr = [Link]([10, 20, 30])


arr[1] = 50
print(arr) # Output: [10, 50, 30]

 Modify slices:

arr[1:3] = [60, 70]


print(arr) # Output: [10, 60, 70]

ACCESSING ROWS AND C OLUMNS

 For 2D arrays:

71
72
Python

arr2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


print(arr2d[1, :]) # Row 1: [4, 5, 6]
print(arr2d[:, 2]) # Column 2: [3, 6, 9]

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

 Use .copy() to create an independent copy:

independent_copy = arr[1:3].copy()

ARRAY MANIPULATION IN NUMPY

INTRODUCTION

 NumPy provides functions to reshape, join, split, and modify arrays for efficient manipulation.

RESHAPING ARRAYS

 Change the shape of an array using reshape():

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]]

 Use -1 to let NumPy infer one dimension:

arr = [Link]([1, 2, 3, 4, 5, 6])

72
Array Manipulation in NumPy 73

print([Link]((3, -1))) # Output: [[1 2], [3 4], [5 6]]

FLATTENING ARRAYS

 Convert multi-dimensional arrays to 1D:

arr = [Link]([[1, 2], [3, 4]])


flat = [Link]()
print(flat) # Output: [1, 2, 3, 4]

JOINING ARRAYS

 Concatenate arrays along an axis:

arr1 = [Link]([1, 2])


arr2 = [Link]([3, 4])
joined = [Link]((arr1, arr2))
print(joined) # Output: [1, 2, 3, 4]

 Stack arrays vertically or horizontally:

vstack = [Link]((arr1, arr2)) # Vertical stacking


hstack = [Link]((arr1, arr2)) # Horizontal stacking

SPLITTING ARRAYS

 Split an array into smaller arrays:

arr = [Link]([1, 2, 3, 4, 5, 6])


split = np.array_split(arr, 3)
print(split) # Output: [array([1, 2]), array([3, 4]), array([5, 6])]

TRANSPOSING ARRAYS

73
74
Python

 Transpose rows and columns:

arr = [Link]([[1, 2], [3, 4]])


transposed = arr.T
print(transposed)
# Output:
# [[1 3]
# [2 4]]

ADDING DIMEN SIONS

 Add new dimensions using [Link]:

arr = [Link]([1, 2, 3])


print(arr[:, [Link]]) # Convert to a column vector

REMOVING DIMENSIONS

 Remove single-dimensional entries using squeeze():

arr = [Link]([[[1], [2], [3]]])


squeezed = [Link](arr)
print(squeezed) # Output: [1 2 3]

CHANGING ARRAY ORDER

 Reverse an array:

arr = [Link]([1, 2, 3])


print(arr[::-1]) # Output: [3, 2, 1]

 Rotate or flip arrays:

arr = [Link]([[1, 2], [3, 4]])


flipped = [Link](arr, axis=0) # Flip along rows

74
Mathematical Operations in NumPy 75

MATHEMATICAL OPERATIONS IN NUMPY

INTRODUCTION

 NumPy provides efficient mathematical operations on arrays, including element-wise operations, aggregate
functions, and linear algebra.

ELEMENT-W ISE OPERATIONS

 Perform operations on corresponding elements of arrays:

import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])

print(arr1 + arr2) # Output: [5, 7, 9]


print(arr1 * arr2) # Output: [4, 10, 18]
print(arr1 ** 2) # Output: [1, 4, 9]

AGGREGATE FUNCTIONS

 Calculate aggregate values:

arr = [Link]([1, 2, 3, 4])


print([Link](arr)) # Output: 10
print([Link](arr)) # Output: 24
print([Link](arr)) # Output: 2.5
print([Link](arr)) # Output: 1
print([Link](arr)) # Output: 4
print([Link](arr)) # Output: Standard deviation
print([Link](arr)) # Output: Variance

TRIGONOMETRIC FUNCTIONS

 Perform trigonometric operations:

angles = [Link]([0, [Link] / 2, [Link]])


print([Link](angles)) # Output: [0, 1, 0]
print([Link](angles)) # Output: [1, 0, -1]

75
76
Python

print([Link](angles)) # Output: [0, undefined, 0]

EXPONENTIAL AND LOGARITHMIC FUNCTIONS

 Compute exponential and logarithmic values:

arr = [Link]([1, 2, 3])


print([Link](arr)) # Exponential: [2.718, 7.389, 20.085]
print([Link](arr)) # Natural log: [0, 0.693, 1.099]
print(np.log10(arr)) # Base-10 log: [0, 0.301, 0.477]

ROUNDING FUNCTIONS

 Round values in arrays:

arr = [Link]([1.234, 2.678, 3.141])


print([Link](arr, 2)) # Output: [1.23, 2.68, 3.14]
print([Link](arr)) # Output: [1, 2, 3]
print([Link](arr)) # Output: [2, 3, 4]

MATRIX OPERATIONS

 Perform matrix-specific operations:

mat1 = [Link]([[1, 2], [3, 4]])


mat2 = [Link]([[5, 6], [7, 8]])

print([Link](mat1, mat2)) # Matrix multiplication


print([Link](mat1)) # Transpose
print([Link](mat1)) # Inverse of a matrix

BROADCASTING

 Perform operations between arrays of different shapes:

arr = [Link]([[1, 2, 3], [4, 5, 6]])


76
Linear Algebra in NumPy 77

print(arr + 10) # Output: [[11, 12, 13], [14, 15, 16]]

COMPARISON OPERATIONS

 Perform element-wise comparisons:

arr = [Link]([1, 2, 3])


print(arr > 2) # Output: [False, False, True]

LINEAR ALGEBRA IN NUMPY

INTRODUCTION

 NumPy provides a submodule, [Link], for performing linear algebra operations such as matrix
multiplication, determinants, eigenvalues, and more.

MATRIX MULTIPLICATION

 Perform matrix multiplication using dot() or @:

import numpy as np
mat1 = [Link]([[1, 2], [3, 4]])
mat2 = [Link]([[5, 6], [7, 8]])

print([Link](mat1, mat2)) # Output: [[19, 22], [43, 50]]


print(mat1 @ mat2) # Same as dot

DETERMINANT OF A MAT RIX

 Compute the determinant using [Link]():

mat = [Link]([[1, 2], [3, 4]])


print([Link](mat)) # Output: -2.0

INVERSE OF A MATRIX

77
78
Python

 Find the inverse of a matrix using [Link]():

mat = [Link]([[1, 2], [3, 4]])


print([Link](mat))
# Output:
# [[-2. 1. ]
# [ 1.5 -0.5]]

EIGENVALUES AND EIGENVECTORS

 Compute eigenvalues and eigenvectors using [Link]():

mat = [Link]([[1, 2], [3, 4]])


eigenvalues, eigenvectors = [Link](mat)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

SINGULAR VALUE DECOM POSITION (SVD)

 Perform SVD using [Link]():

mat = [Link]([[1, 2], [3, 4]])


U, S, V = [Link](mat)
print("U:", U)
print("Singular values:", S)
print("V:", V)

SOLVING LINEAR SYSTEMS

 Solve a system of linear equations Ax=BAx = BAx=B using [Link]():

A = [Link]([[1, 1], [1, -1]])


B = [Link]([6, 2])
x = [Link](A, B)
print("Solution:", x) # Output: [4. 2.]

78
Linear Algebra in NumPy 79

NORM OF A VECTOR OR MATRIX

 Compute norms using [Link]():

vec = [Link]([3, 4])


print([Link](vec)) # Output: 5.0 (Euclidean norm)

TRACE OF A MATRIX

 Compute the sum of diagonal elements using [Link]():

mat = [Link]([[1, 2], [3, 4]])


print([Link](mat)) # Output: 5

RANK OF A MATRIX

 Find the rank using [Link].matrix_rank():

mat = [Link]([[1, 2], [2, 4]])


print([Link].matrix_rank(mat)) # Output: 1

CROSS PRODUCT

 Compute the cross product of two vectors using [Link]():

vec1 = [Link]([1, 2, 3])


vec2 = [Link]([4, 5, 6])
print([Link](vec1, vec2)) # Output: [-3, 6, -3]

DOT PRODUCT

 Compute the dot product of two vectors using [Link]():

vec1 = [Link]([1, 2])

79
80
Python

vec2 = [Link]([3, 4])


print([Link](vec1, vec2)) # Output: 11

RANDOM MODULE IN NUMPY

INTRODUCTION

 NumPy provides a random module for generating random numbers and performing random operations.

GENERATING RANDOM NU MBERS

 Random floats between 0 and 1:

import numpy as np
print([Link]()) # Example Output: 0.5488135039273248

 Random integers:

print([Link](1, 10)) # Random integer between 1 and 9

RANDOM ARRAYS

 1D array of random floats:

print([Link](5)) # Example Output: [0.1, 0.5, 0.3, 0.7, 0.2]

 Multi-dimensional random array:

print([Link](2, 3)) # 2x3 array of random floats

RANDOM SAMPLING

 Random choice from an array:

arr = [Link]([10, 20, 30, 40])


80
Random Module in NumPy 81

print([Link](arr)) # Example Output: 20

 Random choice with replacement:

print([Link](arr, size=3, replace=True))

GENERATING RANDOM NU MBERS FROM DISTRIBUT IONS

 Normal distribution:

print([Link](loc=0, scale=1, size=5)) # Mean=0, StdDev=1

 Uniform distribution:

print([Link](low=0, high=10, size=5))

 Binomial distribution:

print([Link](n=10, p=0.5, size=5)) # Trials=10, Prob=0.5

SHUFFLING AND PERMUT ATION

 Shuffle an array in-place:

arr = [Link]([1, 2, 3, 4])


[Link](arr)
print(arr) # Example Output: [3, 1, 4, 2]

 Generate a random permutation:

arr = [Link]([1, 2, 3, 4])


print([Link](arr)) # Example Output: [2, 4, 1, 3]

81
82
Python

SEEDING THE RANDOM G ENERATOR

 Set a seed to produce reproducible random results:

[Link](42)
print([Link]()) # Output will always be the same

RANDOM STATE

 Use RandomState for independent random streams:

rng = [Link](42)
print([Link](3)) # Example Output: [0.374, 0.950, 0.732]

CUSTOM PROBABILITY DISTRIBUTIONS

 Generate samples with custom probabilities:

arr = [Link]([1, 2, 3, 4])


print([Link](arr, p=[0.1, 0.2, 0.3, 0.4], size=5))

RANDOM BOOLEAN ARRAY

 Generate random booleans:

print([Link]([True, False], size=(3, 3)))

SORTING, SEARCHING, AND COUNTING IN NUMPY

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]()

 Sorts an array without modifying the original array.

import numpy as np
arr = [Link]([3, 1, 4, 1, 5])
print([Link](arr)) # Output: [1, 1, 3, 4, 5]

[Link]()

 Returns the indices of the sorted elements.

print([Link](arr)) # Output: [1, 3, 0, 2, 4]

SORTING MULTI-DIMENSIONAL ARRAYS

 Sort along specific axes:

mat = [Link]([[3, 1, 4], [1, 5, 9]])


print([Link](mat, axis=1)) # Sort each row
# Output: [[1, 3, 4], [1, 5, 9]]

IN-PLACE SORTING

 Use sort() method of the array for in-place sorting.

[Link]()
print(arr) # Output: [1, 1, 3, 4, 5]

SEARCHING IN NUMPY

[Link]()

 Returns indices of elements satisfying a condition.

83
84
Python

arr = [Link]([1, 2, 3, 4, 5])


print([Link](arr > 3)) # Output: (array([3, 4]),)

[Link]()

 Finds the index where a value should be inserted to maintain order.

sorted_arr = [Link]([1, 3, 5, 7])


print([Link](sorted_arr, 4)) # Output: 2

[Link]()

 Returns indices of non-zero elements.

arr = [Link]([0, 1, 0, 3, 0])


print([Link](arr)) # Output: (array([1, 3]),)

COUNTING IN NUMPY

NP.COUNT_NONZERO()

 Counts the number of non-zero elements.

arr = [Link]([0, 1, 2, 0, 3])


print(np.count_nonzero(arr)) # Output: 3

[Link]()

 Returns unique elements and their counts.

arr = [Link]([1, 2, 2, 3, 3, 3])


unique, counts = [Link](arr, return_counts=True)
print(unique) # Output: [1, 2, 3]
print(counts) # Output: [1, 2, 3]

84
Sorting, Searching, and Counting in NumPy 85

[Link]()

 Checks if elements of one array exist in another.

arr1 = [Link]([1, 2, 3, 4])


arr2 = [Link]([2, 4])
print([Link](arr1, arr2)) # Output: [False, True, False, True]

EXAMPLE: COMBINED US AGE

arr = [Link]([3, 1, 4, 1, 5, 9])


print([Link](arr)) # Sorted array
print([Link](arr > 3)) # Indices where elements > 3
print(np.count_nonzero(arr > 3)) # Count of elements > 3
print([Link](arr, return_counts=True)) # Unique elements and counts

85

You might also like