0% found this document useful (0 votes)
21 views156 pages

App Dev Using Python

The document outlines a B.Sc. course on Application Development using Python, covering various units including Python basics, file handling, exceptions, modules, regular expressions, multithreading, GUI programming, web programming, and database programming. It details fundamental concepts such as Python objects, standard types, and built-in functions, along with practical examples and syntax. The course aims to equip students with essential skills for software development using Python.

Uploaded by

thotasravani545
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)
21 views156 pages

App Dev Using Python

The document outlines a B.Sc. course on Application Development using Python, covering various units including Python basics, file handling, exceptions, modules, regular expressions, multithreading, GUI programming, web programming, and database programming. It details fundamental concepts such as Python objects, standard types, and built-in functions, along with practical examples and syntax. The course aims to equip students with essential skills for software development using Python.

Uploaded by

thotasravani545
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
You are on page 1/ 156

B.Sc.

, Honors in Computer Science MAJOR V SEMESTER


Course 15 8: Application Development using Python

UNIT-I

Python basics, Objects- Python Objects, Standard Types, Other Built-in Types, Internal Types, Standard
Type Operators, Standard Type Built-in Functions, Categorizing the Standard Types, Unsupported Types
Numbers -Introduction to Numbers, Integers, Floating Point Real Numbers, Complex Numbers, Operators,
Built-in Functions, Related Modules
Sequences - Strings, Lists, and Tuples, Dictionaries and Set Types Control Flow, Truthiness, Sorting.
List Comprehensions, Generators and Iterators

UNIT-II
Files: File Objects, File Built-in Function [open()], File Built-in Methods, File Built-in Attributes, Standard
Files, Command-line Arguments, File System, File Execution
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context Management, Exceptions as
Strings, Raising Exceptions, Assertions, Standard Exceptions, Creating Exceptions, Why Exceptions (Now)?,
Why Exceptions at All?, Exceptions and the sys Module, Related Modules Modules: Modules and Files,

g
Namespaces, Importing Modules, Importing Module Attributes,

or
Module Built-in Functions, Packages, Other Features of Modules

UNIT-III
s.
te
Regular Expressions: Introduction, Special Symbols and Characters, Res and Python
Multithreaded Programming: Introduction, Threads and Processes, Python, Threads, and the Global
da

Interpreter Lock, Thread Module, Threading Module, Related Modules


p

UNIT-IV
uu

GUI Programming: Introduction, Tkinter and Python Programming, Brief Tour of Other GUIs, Related
an

Modules and Other GUIs


w

Web Programming: Introduction, Wed Surfing with Python, Creating Simple Web Clients, Advanced Web
Clients, CGI-Helping Servers Process Client Data, Building CGI Application, Advanced CGI, Web (HTTP)
w

Server
w

UNIT-V

Database Programming: Introduction, Python Database Application Programmer's Interface (DBAPI),


Object Relational Managers (ORMs), Related Modules.

1 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Unit 1 Python basics, Objects, Numbers and

Sequences Introduction to Python:

Python is a general-purpose, dynamically typed, high-level, compiled and interpreted,


garbage collected, and purely object-oriented programming language that supports
procedural, object. oriented, and functional programming Python is a widely used
programming language that offer Jeveral unique features and advantages compared to
languages like Java and C++.
It is used for:
1.webdevelopment(server side 2.software development, 3.mathematics,

4.system scripting.

g
Q. Python Objects

or
Class: A class is a user-defined data type. It consists of data members (variables) and member

s.
functions, which can be accessed and used by creating an instance of that class. It represents
te
the set of properties or methods that and and used to all objects of one type. A class is like a
blueprint for an object.
p da
uu
an
w
w
w

2 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Objects

In Python, an object is a fundamental concept representing a specific instance of a class. It


encapsulates data (attributes) and behavior (methods) into a single entity. Essentially,
everything in Python is an object, including integers, strings, lists, and functions.

● An object is a basic unit of an object-oriented programming language. An entity that


has state and behavior is called object in Python or other object-oriented
programming languages.

● An object is a basic unit of an object-oriented programming language. An entity that


has state and behavior is called object in Python or other object-oriented
programming languages.

● Here, the state represents properties, and behavior represents actions or


functionality. Hence, objects in Python consist of states or attributes (called data

g
members) and behaviors (called functions). An object is a runtime instance of a

or
defined class. Each instance of an object holds its own relevant data or value,


s.
In Python, an object can refer to anything that can have a name, such as functions,
te
integers, strings, floats, classes, methods, and modules. It is a collection of data, and
methods utilize that data.
da

Characteristics of Object
p
uu

1. State: The specific data held in an object's member variables is called state of the object. It
is also called properties or attributes of the object.
an

It is typically represented by variables. During the execution of a program, the state of an


object may change frequently.
w
w

2. Behavior: The behavior represents functionality or actions that an object can perform. It is
usually represented by functions (or methods) within a class. Methods are used to change
w

the state of an object.

3. Identity: The identity represents the unique name of an object. It differentiates one object
from the other. The unique name of an object is used to identify the object.

Syntax:

class ClassName:

self.attribute1=attribute1

self.attribute2=attribute2

#Method

3 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


def method _name(self):

#Creating an object of the class

object_ name= ClassName(attribute1_value, attribute2_value)

The __init__ Method: We use the __init__ method to initialize the state of an object or to
create an instance of a class. The __init__method requires only self argument, which refers to
the newly generated class instance

Ex:

#Define a class

class Car:

g
def__ init__ (self, brand, model): #The __init__ method.

or
self.brand =brand #Attribute

s.
te
self.model= model #Attribute
da

#Create an object (instance) of the Car class


p

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


uu

#Access attributes
an

print(my_car.brand) # Output: Toyota


w
w

print(my_car.model) # Output: Corolla


w

Output:

Toyota

Corolla

Q. Standard Types

"Standard Types" are typically the most basic, core types like integers, floating-point
numbers, booleans, and characters. "Other Built-in Types" might include more specialized
types that are still part of the language's foundation, such as strings, lists, dictionaries, or sets.

4 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Standard Types: These are the most common and fundamental data types that are typically
built into a programming language's core. Examples include:

● Integers: This data type is represented with the help of int class. It consists of positive
or negative whole numbers (without fractions or decimals). In Python, there's no
limit to how long integer values are often.
Ex:
a=2
print(a, "is of type", type(a))

● Float: The float class represents this type . It is true number with a floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer could even be appended to specify
scientific notation.

g
Ex:

or
s.
b = 1.5 te
print(b, "is of type", type(b))
da

Output: 1.5 is of type


p

● Boolean Data Type:


uu

Boolean data type in Python includes only two values: True and False. These values are used
to represent the truth values of logical expressions. Boolean values are often used in
an

conditional statements and loops to control the flow of a program. To create a Boolean
variable in Python, you simply assign a Boolean value to a variable name:
w

x =True
w

y = False
You can also use comparison operators to create Boolean values:
w

a=5
b=3
c = (a > b)#Output: True
d = (a < b) #Output: False

Complex: This data type stores complex type numbers. Moreover, such numbers have two
parts, real and imaginary. For example, 2+4i, 6-8i, etc.

Q. Other Built-in Types

Data types represent the value type that helps understand what operations you can perform
on a particular piece of data. To define the values of various data types of Python and check
their data types we use the type() function. The following are the standard or built-in data
types in Python:

5 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


● Numeric

g
or
s.
te
p da
uu
an
w
w
w

6 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


● Sequence Type

● Boolean

● Set

● Dictionary

Number Data Type: We store numeric values in this data type. Furthermore, it has three

g
different types as follows:

or
a) Int :It stores all the integer numbers. Moreover, these numbers can be positive or negative
For example, 1, -99, 10, 25, etc.
s.
te
b) Float: This data type stores the real or floating type numbers. This means that it stores all
da

the numbers having decimal values. Moreover, they can be negative or positive. For
example, 4.0, -2.89, 3.45, etc.
p
uu

c) Complex: This data type stores complex type numbers. Moreover, such numbers have
two parts, real and imaginary. For example, 2+41, 6-8, etc.
an

Ex:
a =150
w

print(a value", a) b=20.846


w
w

print("b value", b)

Output:

a value 150

b value 20.846

Sequence Data Types

1. String Data Type:

● A group of one or more characters enclosed in a single, double, or triple quote is


called a string in python

7 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


● A character in Python is just a string with a length of one, there is no character data
type.

Ex:

str "Hello World!" print (str)

Output: Hello World!

2. List Data Type

Python list is an arranged grouping of the same or dissimilar elements that are enclosed by
brackets [] and separated by commas. Use the index number to retrieve the list entries.

To access a particular item in a list, use the index operator [] Ex:

g
list['abcd', 786,2.231 print (list)

or
print (list[0])

Output: ['abcd', 786, 2.23] abcd


s.
te
da
3. Tuple Data Type

A tuple in Pythen is an ordered list of elements, just like a list.


p


uu

● Tuples are not changeable, which is the only difference.


an

● Once created, tuples cannot be changed.


w

● In Python, items of a tuple are stored using parentheses ().


w

● In Python, we utilize the indes number to retrieve tuple items, just like with lists.
w

Ex:

tuple=('abcd, 786,223)

print (tuple)

print (tuple[0])

Output: (abcd, 786, 2.23)

Abcd

8 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Dictionary Data Type

● Python's dictionary is an unordered collection of data values that is used to store


data values in a map-like fashion.

● Unlike other data types, which only include a single value per element, dictionaries
contain a key-value pair.

● The dictionary contains key-value pairs to make it more effective


In a dictionary, a colon (:) separates each key-value pair, while a comma separates
each key A dictionary in Python can be made by enclosing a list of elements in curly
{} braces and separating them with commas.

Ex:

g
dict = {}

or
dict['one'] ="This is one"

dict[2] ="This is two" s.


te
da

print (dict['one'])
p

print (dict[2])
uu

Output: This is one


an

This is two
w

Boolean Data Type:


w
w

One of the built-in data types in Python is the boolean type, which can represent
either True or

False.

Any expression can be evaluated for value using the Python bool() method, which
returns True or False depending on the expression.

Set Data Type:

A set is an unsorted collection of distinct components. This means that set elements
cannot be repeated, and the order in which they are kept is irrelevant.

Sets are changeable, which means that after they are constructed, their elements can
be added or withdrawn. A set's elements, on the other hand, cannot be modified in
place.
9 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Curly brackets are used to define sets.

Ex:

my_set={1, 2, 3,4,5}
print(my_set)
Output {1,2,3,4,5}
Q. Internal Types

Python has several built-in, internal data types that are fundamental to the language.
These types can be broadly categorized as follows:

1. Numeric Types:

● int: Represents integers (whole numbers), e.g., 10, -5, 0.

g
or
● float: Represents floating-point numbers (numbers with decimal points), e.g.,
3.14,
-2.5, 0.0,
s.
te
● complex: Represents complex numbers, c.g., 2+3j, 1-lj.
da

2. Sequence Types:
p
uu

● str: Represents strings (sequences of characters), e.g., "hello", "world", "123"

● list: Represents ordered, mutable sequences of items, e.g... ['a', 'b', 'c'].
an

● tuple: Represents ordered, immutable sequences of items, e.g., (1, 2, 3), ('a',
w

'b', 'c').
w

3. Mapping Type:
w

diet: Represents collections of key-value pairs, e.g., ('a': 1, 'b' 2). (1 'one', 2: 'two')

4. Set Types:

● set: Represents an unordered collection of unique items. frozenset: Represents

an immutable version of set.

5. Binary Types:

bytes: Represents immutable sequences of single bytes, c.g., b"x01\x02\x03'

bytearray: Represents mutable sequences of single bytes, e.g.,


bytearray(b"x01\x02\x03').
10 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
6. Boolean Type:

bool: Represents truth values, either True or False.

7. Other Internal Types:

g
or
s.
te
p da
uu
an
w
w
w

11 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


● NoneType: Represents the absence of a value, with a single value None.

● NotImplemented: Represents a placeholder for operations not supported by


a particular type.

● Ellipsis: Represents a placeholder often used in slicing or type hints.

● Code: Represents compiled Python code, usually not directly manipulated by


programmers.

● Frame: Represents the execution context of a function.

● Traceback: Represents the stack trace of an exception. Slice: Represents a slice

g
object used for indexing.

or
s.
7. None Type: te
✔ NoneType: Represents the absence of a value, often used for default values
da
or to indicate that a variable has no value.

These internal types are fundamental to Python's functionality and are used
p

extensively in various programming tasks. They provide the building blocks for
uu

creating more complex data structures and algorithms.


an

These data types can be further categorized based on their mutability:


w

✔ Mutable: Lists, Sets, Dictionaries, Bytearrays


w

✔ Immutable: Numbers, Strings, Tuples, Bytes


w

Q. Standard Type Operators

Python operators are special symbols used to perform specific operations on one or
more operands.

Types of Python Operators

● Arithmetic Operators

● Comparison (Relational) Operators

● Assignment Operators

● Logical Operators
12 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
● Bitwise Operators

g
or
s.
te
p da
uu
an
w
w
w

13 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


● Membership Operators

● Identity Operators

Arithmetic Operators

Python Arithmetic operators are used to perform basic mathematical operations such
as addition, subtraction, multiplication, etc.

Operator Name Example


+ Addition a+b=30

- Subtraction a-b=-10

g
or
* Multiplication a*b=200

s.
/ Division te b/a=0

% Modulus b%a=0
da
** Exponent a**b=10**20

// Floor division 9//2=4


p
uu

Comparison Operators :Python Comparison operators compare the values on either side of
an

them and decide the relation among them. They are also called Relational operators.
w
w

Operator Name Example


w

== Equal (a==b) is not true

!= Not equal (a!=b)is true

> Greater than (a>b)is not true

< Less than (a<b)is ture

>= Greater than or equal to (a>=b)is not true

<= Less than or equal to (a<=b)is true

Assignment Operators: Python Assignment operators are used to assign values to variables
Following is a table which shows all Python assignment operators.

14 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Operator Name Example

= a=10 a=10

+= a+=30 a=a+30

-= a-=15 a=a-15

*= a*=10 a=a*10

/= a/=5 a=a/5

%= a%=5 a=a%5

Bitwise Operators :Python Bitwise operator works on bits and performs bit by bit operation.
These operaties are used to compare binary numbers

g
or
Operator Name Example

& AND a&b

s.
te
l OR alb

~ NOT ~a
da

<< Zero fill left shift a<<3


p

>> Signed right shift a>>3


uu
an

Logical Operators: Python logical operators are used to combile two or more conditions and
check the final result. There are following logical operators supported by Python language.
w

Assume variable a holds 10 and variable b holds 20 then


Operator Name Example
w
w

and AND a and b

or OR a or b

not NOT not(a)

Membership Operators Python's membership operators test for membership in a sequence,


such as strings, lists, or tuples. There are two membership operators as explained below-

Operator Name Example

in Return true if it finds a a in b


variable in the specified
sequence ,false otherwise
not in Return true if it does not a not in b
finds a variable in the
15 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
specified sequence ,false
otherwise

g
or
s.
te
p da
uu
an
w
w
w

16 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Identity Operators: Python identity operators compare the memory locations of two
objects. There are two Identity operators explained below-

Operator Name Example

is Return true if both variable a is b


are the same object and false
otherwise
is not Return true if both variable a is not b
are the same object and false
otherwise

Q. Standard Type Built-in Functions

Built-in Functions: The Python built-in functions are defined as the functions whose
functionality is pre-defined in Python. The python interpreter has several functions that are

g
always present for use. These functions are known as Built-in Functions. There are several
built-in functions in Python which are listed below:

or
s.
1) abs() Function: The python abs() function is used to return the absolute value of a
number. It takes only one argument, a number whose absolute value is to be returned. The
te
argument can be an integer and floating-point number. If the argument is a complex
da
number, then, abs() retums its magnitude.
Syntax: abs(num)
p
uu

Ex :
an

x=-20
print('Absolute value of -20 is:', abs(x))
w

Output :Absolute value of -20 is: 20


w
w

2) all() Function: The python all() function accepts an iterable object (such as list, dictionary.
etc.). It returns true if all items in passed iterable are true. Otherwise, it returns False. If the
iterable object is empty, the all() function returns True.

Ex:
#all values true
k=[1,3,4.6]
print(all(k))
Output: True

3) sum() :As the name says, python sum() function is used to get the sum of numbers of an
iterable, ie, list.

Ex:
s= sum([1,2,4])

17 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print(s)

Output: 7

4)any() :The python any() function returns true if any item in an iterable is true. Otherwise,

it returns False.

Ex: 1= [4, 3, 2, 0]

print(any(1)) Output True

5)eval(): The python eval() function parses the expression passed to it and runs python
expression(code) within the program.

g
or
Ex:
x-8

s.
te
print(eval(x+1))
6) len(): The python len() function is used to return the length (the number of items) of an
da

object Ex
p

strA = 'Python' print(len(strA)) output 6


uu

7) list(): The python list() creates a list in python.


an

Ex String= 'abcde'
w

print(list(String))
w
w

Output ['a', 'b', 'c', 'd', 'e']

float(): The python float() function returns a floating-point number from a number or string.

Ex print(float(9))

Output 9.0

8) bin(): In python bin() function is used to return the binary representation of a specified
integer A result always starts with the prefix Ob.

Syntax, bin (num)

Ex:

18 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


x = 14

y = bin(x)

print (y)

Output: 061110

9) hex(): In python hex() function is used to return the hexadecimal representation of a


specified integer. A result always starts with the prefix 0x.
Syntax: hex (num)

Ex:

x = 14

g
or
y = hex(x)

print (y)
s.
te
Output: 0xe
da

10) max() Function: The Python max() function is used to retrieve the largest element from
p

the specified iterable. In general max is an operation where we find the largest value among
uu

the given values. For example, from the values 10, 20, 75, 93 the maximum value is 93.
an

Syntax max(x, y, z)
w

Ex: print (“max (80, 100, 1000)":”, max(80, 100, 1000))


print ("max(-20, 100, 400)", max(-20,100, 400))
w
w

Output:

max(80, 100, 1000) 1000 max(-20, 100,400) 400


11) min() Function: The Python min() function is used to retrieve the smallest element from
the specified iterable. In general min is an operation where we find the smallest value among
the given values. For example, from the values 10, 20, 75, 93 the minimum value is 10.

Syntax min(x, y, z)

Ex print ("min(80, 100, 1000), min(80, 100, 1000))


print ("min(-20, 100, 400)", min(-20, 100,400))

Output: min(80, 100, 1000): 80

min(-20, 100, 400): -20

19 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


12) round() Function:

The Python round() function is used to round the given floating point number to the nearest
integer value. The round is done with the specified number of decimal points.

Syntax: round(x[,n])

Ex :print ("round(80.23456, 2) ", round(80.23456, 2))

Output round(80.23456, 2) 80.23

Q. Categorizing the Standard Types


Write the Internal Types Answer (above 3Q)

Q. Unsupported Types
Python is a powerful programming language, but it can sometimes throw unexpected errors,

g
such as the "unsupported operand type(s) for +" error.

or
Understanding the "Unsupported Operand" Error

s.
In Python, the "unsupported operand type(s) for +" error occurs when you try to perform
te
an arithmetic operation, such as addition, on operands of incompatible types. This error is
da

commonly encountered when attempting to add or concatenate objects of different data


types, such as trying to add a string and an integer.
p

Ex:
uu

x=5
y= "LabEx"
an

z=x+y
In this case, the error occurs because you're trying to add an integer(x) and a string (y),
w

which are not supported operand types for the + operator.


w

The operator in Python has different meanings depending on the operand types. For
w

numeric types, such as integers and floats, it performs addition. For string types, it performs
concatenation. However, when you try to mix these operand types, Python raises the
"unsupported operand type(s) for +" error.

Understanding the underlying concept of operand types and their supported operations is
crucial in resolving this error.

Ex2:# Missing Required Discrete Values


20 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
data set[1, 2, None, 4, 5]
sum(data_set)
#Attempting to sum a list containing 'None' (missing discrete value)
Output TypeError: unsupported operand type(s) for + 'int' and 'str'

Solve Error:

Ex: # Corrected Example 3


data_set [1, 2, 0, 4, 5] # Assuming 0 as a replacement for missing value sum(data_set) #
Summing a list of integers without missing values print(sum(data_set))

Output 12

Resolving the "Unsupported Operand" Error:


1) | Convert Data Types: One common solution is to convert the operands to compatible

g
data types before performing the operation. You can use built-in functions like int(),

or
float(), or str() to convert the data types as needed.

Ex:
s.
te
x=5
da

y=”10”
p
uu

z=x+int(y)

print(z)
an

Output: 15
w
w

Separate Numeric and String Operations: If the operation involves both numeric and string
w

operands, you can separate the operations and perform them individually.
Ex:
x=5
y="LabEx"
a=x
b=y
z=a+b
print(z)
Output: 5Lab

Q. Introduction to Numbers (Integers, Floating Point Real Numbers, Complex Numbers)


In Python, the number data type is used to store numeric values. Numbers in Python are an
immutable data type. Being an immutable data type means that if we change the value of an
already allocated number data type, then that would result in a newly allocated object.
Python supports three types of numbers, including integers, floating-point numbers and
complex numbers.

21 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Integers:

Python integers are nothing but whole numbers, whose range dependents on the hardware
on which Python is run. Integers can be of different types such as positive, negative, zero,
and long.

Ex:

I = 123#Positive Integer<br>

J = - 20 #Negative Integer<br>

K = 0 #Zero Integer

g
Long Integers:

or
s.
te
L suffix is used for the representation of long integers in Python. Long integers are used to
store large numbers without losing precision.
da

I=99999999999L
Octal and Hexadecimal:
p
uu

In Python, we also have another number data type called octal and hexadecimal numbers To
represent the octal number which has base 8 in Python, add a preceding 0 (zero) so that the
an

Python interpreter can recognize that we want the value to be in base 8 and not in base 10.
w

Ex I = 11
w

I = 11 #Then in Octal we will write


print (1)
w

Output 9

Performing arithmetic Operations on int type:

Ex :#Addition

res 5+3 #Output: 8

#Subtraction

res-10-4 # Output: 6

#Multiplication

res 7*6 #Output: 42


22 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
#Division

res15/4 #Output: 3.75

#Floor Division

res15/4 #Output: 3

#Modulus (%)

res15%4 #Output: 3 (because 15 divided by 4 gives remainder 3)

#Exponentiation (**)

res 2**3 Output: 8 (because 2 raised to the power of 3 is 8)

g
Floating-point numbers;

or
s.
A floating point number has an integer part and a fractional part, separated by a decimal
point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative
te
number
da

A floating point number is an object of Python's float class. To store a float object, you may
use a literal notation, use the value of an arithmetic expression, or use the return value of
p

float() function.
uu

Ex:
an

a=3.14 # A positive
float b=-0.99 #A negative float
w

c=0.0 #A float value that represents zero


w

Performing arithmetic Operations on float type:


w

#Addition (float)

res=3.5+2.2 # Output: 5.7

#Subtraction (float)

res-7.8-4.3 # Output: 3.5

#Multiplication (float) res=5.52.0 # Output: 11.0

#Division (float)

res=9.0/4.5 # Output: 2.0

23 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


#Floor Division (float) res=9.0/4.5 # Output: 2.0 (it returns the truncated quotient)

#Exponentiation (float)

res=2.5*2 #Output: 6.25 (2.5 raised to the power of 2)

Python Complex Numbers:

A complex number is a number that consists of real and imaginary parts. For example, 2+ 3j
is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary
part.

Performing arithmetic operations on complex type:

To check the result of arithmetic operations, we can simply print the output using print(res).
To check the type of the object, we can use print(type(res)).

g
or
#Addition (complex)
res =( 3 + 4j + (1 + 2j) #output(4+6j)

s.
te
res = (4+ 6j)-(2 + 3j)#output(3+3j)
#multiplication
da

res =(2+3j)*(1+4j)#output:(-10+11j)
#division
p

res =(8+6j)/(2+3j)3output:(2.0+0.0j)
#exponentiation
uu

res=(1+j)***2 #output(0+2j)
#real and imaginary parts of a complex number
an

real=(3+4j).real#output:3.0
imag=(3+4j)imag #output:4.0
Q. Strings
w
w

Strings are one of the most fundamental data types in Python, representing sequences of
w

characters They are used extensively in programming for tasks such as text processing, data
manipulation, an user interaction, we need to know about drings in Python, including basic
operations, string method Formatting, and advanced string manipulation techniques

In Python, a string is a requence of characters enclosed within single quotes (1), double
quotes or triple quotes () Strings are used to represent text data or anything that you enclose
hetwers single or double quotation marks is considered a string A string is essentially a
sequence of array of textual data
Assign String to a Variable : Assigning a string to a variable is done with the variabile name
followed by an equal sign and the string.

Ex.

string =’ Alice’#Single quotes


message ="Hello, world!"# Double quotes
paragraph= ‘’’Python is a programming language’’’# Triple quotes
24 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Accessing Characters: Individual characters within a string can be accessed using indexing,
with

the first character at index 0

Ex:

string110] #Returns

A string 1[4]# Returns’e’

String Operations:

Following are the common string operations that can be performed in Python:
1)Assignment Operator

g
or
Python string can be assigned to any variable with an assignment operator defined with
either single quotes [""], double quotes or triple quotes assigns "string" to variable var name
Python string can be var name string
s.
te
Ex
da

string 1="hello" #Output: hello


p
uu

2. Concatenate Operator"+":
an

Two strings can be concatenated or joined using the operator in Python, as explained in the
below
w

example code
w
w

Ex

string1= "hello"

string2="world"

string combined=string1+ string2

print(string combined)

Output: helloworld

3. String Repetition Operator"*"

The same string can be repeated in Python by n times using stringen, as explained in the

25 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


below

example

string1="helloworld"

print(string1*2)

Output: helloworld helloworld

4. String Comparison Operator"==" & "!="

The string comparison operator in Python is used to compare two strings.


● The “==”operator returns Boolean True if two strings are the same and Boolean
False if two strings are different.

g
● The "!=”operator returns Boolean True if two strings are not the same and returns

or
Boolean False if two strings are the same.

s.
te
Ex:
da

string1= "hello"
p
uu

string2="hello, world"
an

string3= "hello, world"

string4="world"
w
w

print(string1==string4)
w

print(string2==string3)

Output:

False

True

5. Membership Operator "in" & "not in"

The membership operator searches whether the specific character is part/member of a given
input Python string.

● "a" in the string: Returns boolean True if "a" is in the string and returns False if "a" is
not in the
26 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
string.

● "a" not in the string: Returns boolean True if "a" is not in the string and returns False
if "a" is in the string

A membership operator is also useful to find whether a specific substring is part of a given
string.
Ex

string1= "hello world"

print("w" in string1)

print("W" in string1)

g
print("t" not in string1)

or
s.
Output: te
True
da

False
p

True
uu

String Methods: Python provides numerous built-in methods for string manipulation. Some
an

commonly used methods include:


w

● len(); Returns the length of the string.


w

Ex
a ="Hello"
w

print(len(a))

Output :5

● lower(): Converts the string to lowercase

● upper(): Converts the string to uppercase

Ex:

txt= "Hello"

x=txt. upper()

27 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print(x)

Output: HELLO

● strip(): Removes leading and trailing whitespaces

● find(): Returns the index of the first occurrence of a substring

Ex :txt "Hello, welcome to my world"

x=txt.find("welcome")

print(x)

Output :7

g
or
● replace(): Replaces a substring with another string

● split(): Splits the string into a list of substrings. s.


te
da

● join(): Concatenates a sequence of strings.


p

Q. Lists
uu

A list is a collection of ordered and mutable elements enclosed in square brackets || It can
an

contain any type of object, including numbers, strings, other lists, tuples, and dictionaries. In
Python. Lists are one of the most commonly used data structures.
w
w
w

1. A list is a collection of different kinds of values or items. Lists are used to store multiple
items in a single variable.

Ex:

list=["Student", "Teacher", "Parent"]

print(list)

28 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Output: ['Student', 'Teacher', 'Parent']

2. List items are ordered, changeable, and allow duplicate values.

3. List items are indexed, the first item has index [0], the second item has index [1] etc. When
we say that lists are ordered, it means that the items have a defined order, and that order
will not change

4. If you add new items to a list, the new items will be placed at the end of the list

5. The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.

6. List items can be of any data type:

Ex:

g
list1=["apple", "banana", "cherry" ]

or
list2=[1.5, 7, 9, 3]
list3 =[True, False, False]
7. A list with strings, integers and boolean values:
s.
te
Ex:
da

list ["abc", 34, True, 40, "male"]


p

Creating Lists
uu

my_ list=[] #Empty list


an

numbers= [1, 2, 3, 4, 5] # List of integers


w

names= ["Alice", "Bob", "Charlie"] # List of strings


w
w

mixed_list =[1, "hello", 3.14, True] #List of mixed data types

matrix= [[1.2.3], [4,5,6],[7, 8, 9]] #Nested list (list of lists)

Accessing Elements

List elements can be accessed by their index, starting from 0 for the first element. Negative
indices can be used to access elements from the end of the list, where -1 refers to the last
element.

Ex:

numbers= [10, 20, 30, 40, 50]

print(numbers[0]) # Output: 10

29 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print(numbers[2]) #Output: 30

print(numbers(-1]) # Output: 50

List Operations:

There are many different types of operations that you can perform on Python lists,
including:

1. append(): The append() method adds elements at the end of the list. This method can
only add a single element at a time. You can use the append() method inside a loop to add
multiple elements.

Syntax: List name, append(element)

Ex:

g
or
list=[2,5,6,7]

list.append(8)
s.
te
print(list)
da

Output: [2, 5, 6, 7, 8]
p
uu

2. insert():
The insert() method can add an element at a given position in the list. Thus, unlike
an

append(), it can add elements at any position, but like append(), it can add only one
element at a time. This method takes two arguments. The first argument specifies the
w

position, and the second argument specifies the element to be inserted.


w

Ex
w

myList =[1,2,3]

myList.insert(3, 4)

myList.insert(4,5)

print(myList)

Output: [1,2,3,4,5]

3. remove(): The remove() method removes an element from the list. Only the first
occurrence of the same element is removed in the case of multiple occurrences.

Ex:

30 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


myList =[1,2,3]

myList.remove(3)

print(myList)

Output: [1,2]

5 len(): The len() method returns the length of the list, ie, the number of elements in the list.

myList=[1, 2, 3]

print(len(myList)) #Output: 3

6. min() & max(): The min() method returm the minimum value in the list. The max()
method returns the maximum value in the list. Both methods accept only homogeneous lists,

g
Le, lists with similar elements

or
s.
Ex :
myList =[1, 2, 3, 4, 5, 6, 7]
te
print(min(myList))
print(max(myList))
da

Output :1,7
p
uu

7. count(): The function count() returns the number of occurrences of a given element in the
list
an

Ex: myList= [1, 2, 3, 4, 3, 7, 3, 8, 3]


print(myList.count(3))
w
w

Output :4
w

8.concatenate : The concatenate operation merges two lists and returns a single list. The
concatenation is performed using the sign. It's important to note that the individual lists are
not modified, and a new combined list is returned.

Ex:
myList=[1, 2, 3]
yourList [4, 5]
print(myList+yourList)

Output: [1,2,3,4,5]

Features of Lists

• Lists can contain items of different types at the same time (including strings, integers,
floating point numbers and boolean values).
• Lists are mutable and dynamic, list items can be added, removed or changed after
31 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
the list is defined.

• Lists are ordered, newly added items will be placed at the end of the list.

• Lists use zero-based indexing, every list item has an associated index, and the first
item's index is 0.

• Duplicated list items are allowed.

Q. Tuples

Python Tuple is an immutable (unchangeable) collection of various data type elements.


Tuples are used to keep a list of immutable Python objects. The tuple is similar to lists in that
the value of the items placed in the list can be modified, however the tuple is immutable
and its value cannot be changed.

g
Creating a Tuple

or
s.
A tuple is formed by enclosing all of the items (elements) in parentheses () rather than square
brackets | 1, and each element is separated by commas. A tuple can contain any number of
te
objects of various sorts (integer, float, list, string, etc.). A tuple can include elements with
different data types. You can also specify nested tuples, which have one or more entries that
da

are lists, tuples, or dictionaries


Ex:
p
uu

num =(100, 35, 7, 21) # tuple with integer values


an

print(num)
w

my_tuple =(23.545, Hello, 'A' 785) #tuple with mixed values


w

print(my_tuple)
w

Output:
(100,35, 7, 21)
(23.545, 'Hello', 'A', 785)

Tuple Operations

1. How to Access Tuple Elements in Python

In Python, tuples are immutable lists of elements enclosed in parentheses. Different


techniques can be used to access individual items within a tuple

Ex:

fruits=("apple", "banana", "cherry")


32 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
second_fruit= fruits[1] # Access the second element (banana)

print(second_fruit) # Output: banana

last_fruit =fruits[-1] # Access the last element (cherry)

prin(last_fruit)

Output: banana

cherry

2. Updating Tuples in Python

You can update an element by slicing the original tuple and substituting the new value for

g
the desired element. Tuple concatenation is another tool you can use to join the modified

or
and original items together.

Ex:
s.
te
tup1 =(16, 44.26);
da

tup2 =('abc', 'xyz');


p
uu

tup3=tup1+tup2;
an

prin (tup3)
w

Output: (16,44.26, 'abc' 'xyz)


w

This code creates a new tuple called tup3 by combining two defined tuples, tupl and tup2. It
w

shows that while merging tuples is okay, changing a tuple is restricted.

3. Delete Tuple Elements in Python

The process of deleting the complete tuple object from memory is referred to as "delete
tuple" in Python. This is not the same as removing specific tuple elements, which cannot be
done because of their immutability.

Ex:

Original_tuple= ("apple", "banana", "orange", "grapefruit")


deleted_tuple= original_tuple[1:]
print("Original tuple:", original_tuple)

print("Deleted tuple:", deleted_tuple)


33 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Output:

Original tuple: ('apple', 'banana', 'orange', 'grapefruit")


Deleted tuple: ('banana', 'orange', 'grapefruit)

4. Repetition operator (*): It is known as repetition operator. It concatenates the multiple


copies of the same tuple.

Ex: t1=(1,2,3)

print(t1*4)

output: (1,2,3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

5 .In: It is known as membership operator. It returns if a particular item is present in the


specified

g
or
tuple
Ex :
t1=(1,2,3,4,5,6)
s.
te
print(5 in t1)
da

print(10 in t1)
p

Output: True
uu

False
an

6. not in : It is also a membership operator and It returns true if a particular item is not
w

present in the tuple


w

Ex
w

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

#not in operator

print(4 not in 11)

print(10 not in 11)

Output

False

True

34 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Tuple Methods:

1)len() function: The len() function is used to return the number of elements in a tuple.

Ex: my_tuple =(1,2,3,4,5)

print(len(my_tuple)) #Output: 5

2. max() function: The max() function is used to return the maximum value in a tuple.

Ex:

my_tuple =(5,6,7,8,9)

print(max(my_tuple))

g
Output: 9

or
s.
3. min() function: The min() function is used to return the minimum value in a tuple. It takes
a tuple as an argument and returns the minimum value in the tuple.
te
da
Ex:
p

my_tuple =(5, 6, 7, 8, 9)
uu

print(min(my_tuple))
an

Output: 5
w

4. sum() function: The sum() function is used to return the sum of all elements in a tuple.
w

Ex: my_tuple =(1, 2, 3, 4, 5)


w

print(sum(my_tuple))

5. count(): This method returns the number of occurrences of an element appearing in a


tuple.

Syntax: my_tuple.count(x)

Ex:

my_tuple =(1, 2, 3, 4, 2, 5, 2)

count=my_tuple.count(2)

print(count)
35 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Output: 3

Q. Dictionaries

A dictionary in Python is a group of key-value pairs, sometimes referred to as a hash table.


Every key is distinct and corresponds to a single value. Dictionary entries can have their
values modified after they are created, which is known as mutability. Data is organized and
stored using dictionaries.

Dictionary in Python are changeable data structures that help to store key-value pairs. These
don't contain any duplicates, and they are ordered in format.
Creating the dictionary using the dict() command or curly braces {} is easy. After creating the
dictionary, it is easy to add, remove, or manipulate the dictionary

The key should be a single element, and the values can be of any kind, from integer, tuple,

g
list, etc.

or
s.
te
p da
uu
an

Creating a Dictionary
w

In Python, it is easy to create a dictionary, add the items inside the curly braces and assign
w

them to a variable name. The items will be in the form of key, value pairs, you need to
w

separate each item with a comma

Syntax: Variable_name={ key:value, key:value, key :value, etc}

Example:

#We will follow this syntax


#student_marks= {"ID":total_marks}
student_marks={"20":250, “21”:265, "22":278, "23" 249, "24":280}

print("\nList of students with total marks obtained:")

print(student_marks)

Output: List of students with total marks obtained: {"20":250, "21:265, "22" 278, "23" 249.
24:280}
36 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Dictionary Operations

Creating Dictionaries: Python creates a dictionary using curly braces () and key-value pairs

separated by colons.

Ex

#Creating a dictionary of ages

ages={"Alice": 28, "Bob": 35, "Charlie":42}

#Creating an empty dictionary empty_dict()

Accessing Dictionaries: To access an element in a dictionary, you can use square brackets []

g
and

or
the element's key.

Ex:
s.
te
da
#Accessing the age of Alice

alice_age= ages["Alice"]
p
uu

print(alice_age)
an

Adding Elements: To add a new key-value pair to a dictionary, you can use square brackets
[] and
w

assign a value to the new key:


w

In Python, the assignment opcrator (") is the most popular and straightforward way to add
w

elements to a dictionary.

This method includes directly assigning the required value to the specified key within the

dictionary.

Ex: Adding a new element to the dictionary

ages["David"]=21

print(ages)

Updating Elements: To update an existing element, you can use the same syntax: #Updating

an element in the dictionary


37 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
ages["Bob"]=36

print(ages)

Removing Elements :To remove an element from a dictionary, you can use the del keyword
or the

pop() method
Ex:
#Removing an element with del

del ages["Charlie"] # Removing an element with pop()

alice_age = ages.pop("Alice")

g
print(ages)

or
print(alice_age)

Dictionary Methods s.
te
da

The Python dictionary provides a variety of methods and functions that can be used to
easily perform operations on the key-value pairs. Python dictionary methods are listed
p

below.
uu

Methods Description
an

clear() Removes all the elements from the


dictionary
w

copy() Returns a shallow copy of the specified


dictionary
w

has_key() Returns true if the key exists in the


w

dictionary, else returns false


items() Returns a list of dictionary item in (key ,
value) format pairs
keys() Returns a list containing all the keys in the
dictionary
pop(key) Removes and returns an element from a
dictionary having the given key
update() Updates the dictionary by adding key-value
pair

Advantages:

1. Efficiency: Dictionaries excel at rapid data retrieval and searching. They achieve this by
employing a hash table for data storage, permitting constant-time access to values, regardless
of dictionary size.

38 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


2. Flexibility: Dictionaries accommodate a wide range of data types, rendering them a
versatile choice for data organization.

3. Readability: Dictionaries feature a user-friendly and easily comprehensible structure,


making them well-suited for storing and retrieving data in a human-readable format.

Q. Set Types

In Python, a set is a built-in data type used to store an unordered collection of unique
elements. Sets are mutable, meaning elements can be added or removed after the set is
created, but the elements themselves must be immutable types such as numbers, strings, or
tuples. Sets are defined using curly braces {} or the set() constructor.

A Set in Python is used to store a collection of items with the following properties.

g
● No duplicate elements. If try to insert the same item again, it overwrites previous

or
one.


s.
An unordered collection. When we access all items, they are accessed without any
te
specific order and we cannot access items using indexes as we do in lists.
da

● Internally use hashing that makes set efficient for search, insert and delete operations.
It gives a major advantage over a list for problems with these operations.
p
uu

● Mutable, meaning we can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.
an

Syntax:
w

variable_name= {"string", value, number} OR variable_name =set([value, value, value])


w
w

Create Sets in Python

To create sets in Python, place all the elements within curly braces {}, separated by commas.
A set can include unlimited items, such as integers, floats, tuples, and strings. However,
mutable elements such as lists, sets, and dictionaries cannot be used as elements within a set.

1. Using Set Method

my_set= set(“ HELLO” )

print(my_set) # Output :{‘H' , ‘ E’ ,’L’ , ‘L’,’O’}

2. Using Curly Braces:

employee_id = {12, 14, 16, 18}

39 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print('Employce_ID:’,employee_id)

Output: Employee_ID: (16,18,12,14)

Set Operations

Set Union:
It is a function that returns a set with all elements of the original set and the specified sets.
Since it returns a set, all items will have only one appearance. The item will appear only once
if two sets contain the same value.

g
or
Ex :A1 = {24, 35, 34, 45}
A2 = {24, 56, 35, 46}
A3 = {24, 35, 47, 56}
print(A1.union(A2, A3)) #Output: {34,35,45,46,47,24,56} s.
te
da

2. Set Intersection: It is very different from the previous method's built-in set. In this case, only
the elements common in both sets or multiple sets (in case of more than two sets) are usually
p

returned as a set.
uu
an
w

Ex:
w

A1= {24, 35, 34, 45}


w

A2= {24, 56, 35, 46}

A3= {24, 35, 47, 56}

print(Al.intersection(A2, A3))

Output: {24,35}

3. Set Difference:

This is a very important function inset. This function returns a set which is the difference
between two sets. Remember that here difference does not mean subtraction because it is
the difference between the number of elements in two sets and not the values of elements.
For example, set Al - set A2 means it returns a set with elements present in Al but not in A2.
40 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Ex:

A1= {24, 35, 34, 45}

A2= {24, 56, 35, 46}


print(Al.difference(A2))

print(A2.difference(A1))

g
or
Output: {34,45}

{56,46} s.
te
p da
uu
an
w
w
w

41 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Built-in Functions with Set

Here are some of the popular built-in functions that allow us to perform different operations
on a set.

Functions Description

all() Returns true if all the elements of the set are true(or if the set is empty )

len() Returns the length (the number of items) in the set

max() Returns the largest item in the set

min() Returns the smallest item in the set

sorted() Returns a new sorted list from elements from the set

sum() Returns the sum of all the elements in the set

g
or
Q. Flow of Control

s.
A program's control flow is the order in which the program's code executes.
te
The control flow of a Python program is regulated by conditional statements, loops, and
function calls.
da

Python has three types of control structures:


p
uu

• Sequential-default mode
an

• Selection - used for decisions and branching


w

• Repetition - used for looping, i.e., repeating a piece of code multiple times.
w

1. Sequential: Sequential statements are a set of statements whose execution process happens
w

in a sequence. The problem with sequential statements is that if the logic has broken in any
one of the lines, then the complete source code execution will break.
Ex: a=20
b=10
c=a-b
print("Subtraction is ",c)

Output: Subtraction is 10

2. Selection/Decision control statements

In Python, the selection statements are also known as Decision control statements or
branching statements.

42 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Types of Decision control statements

a) if statement: The if statement is one of the most well-known control flow statement
types. It checks a condition and executes one of two functions:

• If the set condition is True, the code in the following block is executed.

• If the set condition is False, the code in the following block is ignored

g
or
s.
te
.
p da

Ex:
uu

i=10
if (i > 15):
an

print("10 is less than 15")


print("I am Not in if")
w
w

b) if-else: The if-else statement evaluates the condition and will execute the body of if if the
test condition is True, but if the condition is False, then the body of else is executed.
w

Ex:
43 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
n = 20
if n% 2 ==0:
print("n is even")
else:
print("n is odd")

Output: n is even

c) Nested if: Nested if statements are an if statement inside another if statement. Syntax:

g
or
s.
te
p da

if (condition-1):
uu

if (condition-2):
……..
an

……..
else:
w

…….
w

…….
w

else:
…….
…….

Ex:

a = 20
b = 10
c = 15
if a>b:
if a >c:
print("a value is big")
else:
print("c value is big")
elif b >c:

44 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print("b value is big")
else:
print("c is big")

Output: a value is big

3. Repetition: A repetition statement is used to repeat a group(block) of programming


instructions. In Python, we generally have two loops/repetitive statements.
• for loop

• while loop

for loop: A for loop is used to iterate over a sequence that is either a list, tuple, dictionary,
or
a set. We can execute a set of statements once for each item in a list, tuple, or dictionary.

g
or
s.
te
p da
uu
an

Ex:
w

lst=[1, 2, 3]
w

for i in range(len(1st)):
w

print(Ist[i], end="\n")
Output:
1
2
3

while loop: In Python, while loops are used to execute a block of statements repeatedly until
a given condition is satisfied. Then, the expression is checked again and, if it is still true, the
body is executed again. This continues until the expression becomes false
.

45 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex:

m=5
i=0
while i <m:

g
print(i, end = "")

or
i=i+1
print("End")
Output :01234 End
s.
te
Q. Truthiness
da

In Python, "truthiness" refers to how values are evaluated in a boolean context, such as in if
p

statements or boolean operations. Every object in Python has a truth value, which is either
uu

True or False.
an

Default Truthiness:
w

• By default, most objects are considered "truthy"


• Empty collections (lists, tuples, dictionaries, sets, strings) are considered "falsy" The
w

number zero (0) is considered "falsy”.


w

• None is considered "falsy"

• All other numbers (including negative numbers) are considered "truthy"

Truthiness is Determined:

• Python first checks if an object has a bool() method. If it does, this method is called
to determine the truth value.

• If __bool__ () is not defined, Python checks for a len() method. If present, the truth
value is determined by whether the length of the object is zero (falsy) or non-zero
(truthy).

• If neither __bool__ () nor __len__ () are defined, the object is considered truthy.

46 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex

print(bool(0)) # Output: False

print(bool(1)) # Output: True

print(bool(-1)) #Output: True

print(bool(""))#Output: False

print(bool("hello")) # Output: True

print(bool([])) #Output: False

print(bool([1,2])) #Output: True

g
or
print(bool(None)) # Output: False

s.
te
Custom Objects: You can control the truthiness of custom objects by implementing
the_bool_() method in your class. This method should return True or False based on your
da

desired logic.
p

Use Cases:
uu

• Truthiness is commonly used in conditional statements (if, elif, while) to check if a


an

value is "empty" or "zero"


w

• It allows for more concise code, as you can directly use objects in boolean contexts
w

without explicit comparisons.


w

Q. Sorting

Sorting in Python is a way to arrange things in a specific order. You can organize the data in
ascending or descending order according to your need. Sorting is very helpful when finding
particular items in your data. There are two ways to sort your data using a built-in function
in Python:

1) sort() function

2) sorted() function.

Ex:

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

47 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


sorted_numbers = []

while numbers:

minimum= numbers[0] # Set the first element as the current minimum

for x in numbers:

#If any element is smaller than the current minimum, then update the minimum

if x < minimum:

minimum =x

#Add minimum to the sorted numbers list

g
sorted_numbers.append(minimum)

or
s.
#remove minimum from the numbers list te
numbers.remove(minimum)
da

print(sorted_numbers)
p
uu

Output:[1,2,3,5,6,8,9]
Explanation:
an

Given elements: 3 6 1 8 2 9 5
Step 1 : 3 6 8 2 9 5 1
w

Step 2 : 3 6 8 9 5 1 2
Step 3 : 6 8 9 5 1 2 3
w

Step 4 : 6 8 9 1 2 3 5
Step 5 : 8 9 1 2 3 5 6
w

Step 6 : 9 1 2 3 5 6 8
Step 7 : 1 2 3 5 6 8 9

Sort() Function in Python

The sort() method in Python can sort a list of elements in a specific order. By default, this
function sorts elements in ascending order You can also use parameters to sort items in a
different order according to your requirements, like from largest to smallest. The sort()
function modifies the existing input list and does not return a new one.

48 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The sort() function compares the first two elements of the list and swaps them if they are not
in order It then compares the next element with the first element, switches them if necessary,
and moves on to the next element until the entire input list is sorted.

Syntax: list_name.sort(reverse=False, key=None)

Ex 1: Sorting a list of integers in ascending order

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

numbers.sort()

print(numbers)

OUTPUT: [1, 1,2,3,3,4, 5, 5, 5, 6, 91

g
or
s.
te
p da
uu
an
w
w
w

49 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Sorted() Function in Python

The sorted function is used to sort a list of elements in ascending or descending order. It
takes an iterable object (a list or tuple) as input and returns a new sorted list. By default, the
sorted function sorts elements in ascending order, but you can specify the reverse True
argument to sort in descending order according to your need. Be careful when sorting vast
input, as very long lists can be relatively slow.
Syntax: sorted(iterable, key =None, reverse=False)

Ex: Sorting a list of numbers in ascending order

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

sorted_numbers =sorted(numbers)

g
print(sorted_numbers)

or
Output: [1.1.2.3.3,4,5,5,5,6.9]

Types of Sortings:
s.
te
da
1) Bubble Sort: It is a comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order
p

Advantages
uu

• We can swap the data elements without consumption of short-term storage, It


an

requires less space.


w
w

2) Merge Sort: Merge sort first divides the array into equal halves and then combines them
in a sorted manner.
w

Advantages

• The file size does not matter for this sorting technique.

This technique is good for the data which are generally accessed in a sequence order. For
example, linked lists, tape drive, etc.

3) Insertion Sort: Insertion sort involves finding the right place for a given element in a
sorted list. So in beginning we compare the first two elements and sort them by comparing
them. Then we pick the third element and find its proper position among the previous two
sorted elements. This way we gradually go on adding more elements to the already sorted
list by putting them in their proper position.

Advantages
50 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
• It is simple and easy to implement.

g
or
s.
te
p da
uu
an
w
w
w

51 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


• It performs well while dealing with a small number of data elements.

4) Selection Sort: In selection sort we start by finding the minimum value in a given list and
move it to a sorted list. Then we repeat the process for each of the remaining elements in
the unsorted list. The next element entering the sorted list is compared with the existing
elements and placed at its correct position. So, at the end all the elements from the unsorted
list are sorted.

Q. List Comprehensions

List comprehension in Python is a single line of code that we write inside the square brackets.
It is popularly known as the one-liner code. And, List comprehension offers a shorter and
simpler syntax for constructing new lists based on values in existing lists. Besides creating lists,
we can filter and transform data using list comprehension, which has a more human-
readable and concise syntax.

g

or
It lets you create clear, simple code on a single line as opposed to several lines filled
with loops in Python.

• s.
You can also add conditions to filter which elements should be included in the new
te
list.
da

• List comprehension in Python is faster and more efficient than traditional loops for
p

creating lists.
uu

• It is great for transforming data, such as squaring numbers, filtering even or odd
an

numbers, or manipulating strings.


w
w

Syntax: mylist=[output/expression for item in iterable if condition True]


w

List comprehension mainly has three components:

1. For loop: It is mandatory and loops over the given iterable.


2. Condition and expression: It is optional and is used to imply some condition over the
iterable

3. Output: It is mandatory and the variable(or expression) we provide as output is added to


our list.

when to use list comprehension in Python

• To filter an existing list.

• To generate a list of data

52 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Example of Simple List Comprehensions in Python

def simplest_list_comp(ls):

g
or
s.
te
p da
uu
an
w
w
w

53 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


mylist [i for i in ls]

print("My list is:",mylist)

simplest_list_comp([1,5,6,7,8,9])

Output: My list is: [1, 5, 6, 7, 8, 9]

Explanation:

In the above example, we have a for loop which iterates over the passed list. However, we
do not have any conditions here.

For output, we have passed i. So, our output is simply the elements of the iterable in our
new list.

g
or
Adding Some Conditions to Above Code-- Let us now add some conditions to our previous
code and check how it works.

Ex: s.
te
da

def simplest_list_comp(ls):
p

#adding a condition to check if


uu

#the element is an odd or even number


mylist[i for i in Is if i % 2 = 0]
an

print("My list is:",mylist)


w

simplest list comp([1,5,6,7,8,9,10,11,12])


w
w

Output: My list is: [6, 8, 10, 12]

Explanation: Did you just see, that we added a condition that checks if the elements of our list
are even or odd? So this time, our list filters only the even numbers from the list passed as
parameters and adds to our new list.

Also, you must note that using list comprehension we are creating a completely new list
based on our conditions, iterables, etc. However, we DO NOT MODIFY the original list
passed to us as the "iterable"

Using our Regular For Loops : For better understanding, you can also refer to the same
below code, which is written without using list comprehensions (using only for loop):
Ex:

def simplest_list_comp(Is):

54 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


#using our regular for loops
mylist = []
for i in ls:
if i%2==0;
i = i**2
mylist.append(i)

print(mylist)

simplest_list_comp([1,5,6,7,8,9,10,11,12])

So, you must have seen, how this multi-line code was written in a single line using the list
comprehension.

Difference Between 'for' Loop vs. List Comprehension

g
or
Aspect For loop List comprehension

s.
syntax Requires multiple lines of code te Uses a single line of code

performanc Generally slower due to more overhead Typically,its faster as its


e optimized internally
da

Code length It requires more lines It is more concise than a


loop
readability It can be more verbose and harder to follow More readable for simple
p

iterations
uu

Use case Suitable for complex logic and multiple Best for simple
actions transformation or filtering
an

flexibility More flexible for handling complicated logic Less flexible but great for
straightforward tasks
w

Advantages of List Comprehension


w
w

• It allows us to write concisely within a single line of code. It makes the code easier to

read and understand.

• It is rather less complex than traditional for loops, as it doesn't have temporary
variables and separate loop constructs.

• In many cases, list comprehensions can be seen as having higher performance than
traditional loops.

• They support a wide range of operations like filtering, mapping, and nesting.

Q. Generators and Iterators

Iterator: An iterator is an object which contains a countable number of values. The iterator

55 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


can traverse through all values, meaning it's an object it can iterate upon. Technically it can
be defined as an iterator, an object used to implement the iterator protocols. Also, an
iterator can be defined as a repeating process, which is repeated many times using the same
logic as applied.

g
or
s.
te
p da
uu
an
w
w
w

56 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The primary purpose of the iterator is to allow every element of the container to use when it
is isolated from the internal structure of the container. This way enables the container which
stores the details in any manner. So, in this case, it treats the user as a simple sequence or a
list. Iteration can be achieved by using a loop like for, etc.

There are two methods used here.

_iter_()

_next _()

Iterator uses the_ next_() method when iterating over the iterable object.

In _next_() method returns the next item of the object. Note that every iterable is not an
iterator A

g
good example is taken, for it is considered a list.

or
s.
Using iter() can create an iterator from iterable. Making it possible requires an object for
class and either a method_iter _It returns an iterator or a_ get item _using a method with
te
sequential indexes that starts with 0.
da

Ex:
p

iterator_test= iter([10, 20, 30, 40, 50])


uu

print(type(iterator_test))
an

print(next(iterator_test))
w
w

print(next(iterator_test))
w

print(next(iterator_test))

print(next(iterator_test))

print(next(iterator_test))

#Once the iterator is exhausted, next() function raise Stoplteration.

print(next(iterator_test))

Output:

<class 'list _iterator’>

10
57 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
20

30

40

50

Stoplteration --

In the above example first created an iterator named iterator_test. Then pass a list of
numbers using the method iter(). After that, use the type() method to check the type. So
here found an indeed iterator more than a list iterator(). The next() method produces an
integer on each iteration and stops until an exception occurs.

g
Iterable

or
Iterable is also an object which can iterate over. It's generated by using the _iter_() method.

s.
It's inherited from iterations. It is to be looped over or iterated over with the help of a for
loop used.
te
da
Examples of iterable are the objects like lists, tuples, sets, dictionaries, strings, etc.. Iterable
also says anything that you can loop over.
p

For Example:
uu

1.# String as an iterable


an

for i in PYTHON
w
w

print(i)
w

2. # list as an iterable
for i in [1, 2, 3,4]:

print(str(i*2)) Output:

1. P
Y
T
H
O
N

2. 2
4
6

58 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


8

Generators: Building an iterator in Python requires a significant amount of effort. We must


create a class containing_iter_() and _next_() methods, keep track of internal states and raise
Stoplteration when no values are returned. This is both long and contradictory. In such
cases, the generator comes to the rescue.
Python has a generator that allows you to create your iterator function. A generator is
somewhat of a function that returns an iterator object with a succession of values rather than
a single item A yield statement, rather than a return statement, is used in a generator
function.

The difference is that, although a return statement terminates a function completely, a yield
statement pauses the function while storing all of its states and then continues from there on
subsequent calls.

g
diagram

or
Example 1:

s.
te
#Program to print the Power of two up to the given number
da

def Power TwoGen(max=0): n=1 while n < max: yield 2** n n+=1 #Printing the values
stored in a
p
uu

a Power TwoGen(6) for i in a:


an

print(i) Output:
w

24
w

8 16 32
w

Difference Between Iterators and Generators

Iterators generators

Iterators are the objects that use the A generator is a function that produces
next()method to get the next value or yields a sequence of values using a
of the sequence yield statement
Classes aree used to implement the Functions are used to implement the
iterators() generators
Every iterator is not a generator Every generator is an iterator

Complex implementation of Generators in python are similar to code


iterator protocols .i.e.,iter () and then do the custom iterator using the
next () yield statement
Iterator in python are less memory Generators in python are more memory
efficient efficient

59 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Non local variables are used in All the local variables are stored before
iterator the yield statement .

g
or
s.
te
p da
uu
an
w
w
w

60 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


UNIT-II

Q )File Objects

Python File handling is an essential concept in Python's programming framework. It enables


you to use your Python code directly to create, read, write, and manage files. The ability to
handle data storage, retrieval, and modification in a flexible manner facilitates the
management and processing of huge datasets.

Types of Files in Python

1. Text files: Typically ending in.txt, these files contain data in a readable format for humans
to

g
access.

or
s.
• Any text editor can be used to edit the plain text that they contain.
te
• Text files can be handled in Python utilizing modes like a for appending, w for
da
writing, and r for reading.

2. Binary Files:
p
uu

• Unlike text files, binary files contain data like pictures, films, or computer programs
that are not readable by humans. .bin or.dat are typical extensions for them.
an

• Python handles similar to text files, binary files with the addition of a b suffix, such as
w

rb for reading binary files and wb for writing them.


w

File Objects:
w

A file object is an object in Python that gives access to files. These could be the on-disk files,
meaning files in the hard disk, or files present in other storage and communication devices.
Once such a file object is created, then we can use different methods like read() and write(),
to read from
and write to the files, respectively.

Create a file object: You create a file object using the open() built-in function. In the "open()"
function, you also provide certain parameters or values within the parenthesis.

The file object can be closed using the close() method: After the file object has been created
and contents have been read or written to the file, we need to close the file object. The file
object can be closed using the close() method.

File Operations in Python


61 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
1.) Opening Files in Python: To open a file using both relative and absolute paths. Different
file access modes for opening a file read and write mode.

syntax
file = open("filename", "mode")

Where, filename is the name of the file to open and mode is the mode in which the file is
opened (e.g., 'r' for reading, 'w' for writing, 'a' for appending).

2.) Working in Read mode :Reading a file in Python involves opening the file in a mode that
allows for reading, and then using various methods to extract the data from the file. Python
provides several methods to read data from a file -

a) read()-Reads the entire file.

g
b) readline()-Reads one line at a time.

or
s.
c) readlines-Reads all lines into a list. te
Ex:
Using read() method
da

with open("example.txt", "r") as file:


p
uu

content file.read()
print(content)
an

Output :
w

Welcome to College
w

3.) write() Function: To write to a Python file, we need to open it in write mode using the w
w

parameter. To write data to a file, use the write() or writelines() methods.

Ex:

with open("foo.txt", "w") as file:

file write("Hello, World!")

print ("Content added Successfully!!")

Output: Content added Successfully!!

4.) Closing Files in Python: We can close a file in Python using the close() method. It is
important to close files after operations are completed to prevent data loss and free up system
resources.

62 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex:

file =open("example.txt", "w")

g
or
s.
te
p da
uu
an
w
w
w

63 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


file.write("This is an example.")

file.close()

print ("File closed successfully!!")

Output :File closed successfully!!

Q. File Built-in Function [open ()]

Python has a built-in function open() to open a file. Which accepts two arguments, file name
and access mode in which the file is accessed. The function returns a file object which can be
used to perform various operations like reading, writing, etc.

Syntax Fileobject open (file-name, access-mode)

g
or
• file-name: It specifies the name of the file to be opened.


s.
access-mode: There are following access modes for opening a file:
te
da

Access Descrption
mode
p

“w” Write – opens a file writing, creates the file it doesnot exist
uu

“r” Read-default value.opens a file for reading error if the file


doesnot exist
an

“a” Append-open a file for appending , creates the file if doesnot


exist
“x” Create-create the specified file,returns an error if the file exist
w
w

“w+” Open a file for updating,overwrite if the file exist


w

“r+” Open a file for updating doesn’t overwrite if the file exists

Q. File Built-in Methods


Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. For this, python provides
following built-in functions, those are

• close()

• read()

• readline()

• write()

64 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


• writelines()

• tell()

• seek()

Close(): The close() method used to close the currently opened file, after which no more
writing or Reading can be done. Python automatically closes a file when the reference object
of a file is reassigned to another file. It is a good practice to use the close() method to close a
file.

Syntax :Fileobject.close()

Read(): The read () method is used to read the content from file. To read a file in Python,
we must open the file in reading mode.

g
Syntax: Fileobject.read([size])

or
s.
Where 'size' specifies number of bytes to be read. te
readline(): Python facilitates us to read the file line by line by using a function readline(). The
readline() method reads the lines of the file from the beginning, i.e., if we use the readline()
da

method two times, then we can get the first two lines of the file.
p

Syntax :Fileobject.readline()
uu

write(): The write () method is used to write the content into file. To write some text to a
an

file, we need to open the file using the open method with one of the following access
modes.
w
w

• w: It will overwrite the file if any file exists. The file pointer point at the beginning of
the file in this mode.
w

Syntax: Fileobject.write(content)

• a: It will append the existing file. The file pointer point at the end of the file.

writelines(): The writelines () method is used to write multiple lines of content into file. To
write some lines to a file

Syntax: Fileobject.writelines(list)

Here list This is the Sequence of the strings.

Ex:

f=open("myfile.txt", "w")

65 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


f.writelines(["Python supports Files \n", "python supports Strings."])

f.close()

Output

Python supports Files

python supports Strings.

Tell(): The tell() method returns the current file position in a file stream. You can change the
current file position with the seek() method.

Syntax:

g
Fileobject.tell()

or
myfile.txt

s.
te
function open() to open a file.
da

method read() to read a file.


p

Ex:
uu

f=open("myfile.txt", "r")
an

print(f.readline())
w

print(f.tell())
w
w

f.close()

Output: 33

seek(): The seek() method sets and returns the current file position in a file stream.

Syntax:

Fileobject.seek(offset)

EX:

f= open("myfile.txt", "r")

print(f.seek(9))
66 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
print(f.read())

f.close();

Output:

open() to open a file.


method read() to read a file.

Close(): This function closes the file. A file, once it gets closed, can no more be used for
reading or writing.

Q. File Built-in Attributes File Built-in Attributes

File objects also have data attributes in addition to its methods. These attributes hold
auxiliary data related to the file object they belong to, such as the file naFme (file.name), the

g
mode with which the file was opened (file.mode), whether the file is closed (file.closed), and

or
a flag indicating whether an additional space character needs to be displayed before

s.
successive data items when using the print statement (file.softspace).
te
File object attributes Description
da

file.closed 1 if file is closed ,0 otherwise

file.mode Access mode with which file was opened


p
uu

file.name Name of file

file.softspace 0 if space explicity


an
w

Example:
w

f=open ("myfile.txt", "r")


w

print(f.name)

print(f.mode)

print(f.closed)

f.close()

print(f.closed)

Output:

myfile.txt

67 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


r

False

True

Q. Standard Files

Standard files in Python refer to the way Python handles input and output operations.
Python treats every input and output as a file, allowing for a consistent way to interact with
various data streams. These standard files are automatically available when a Python
program runs.

• Standard files in Python refer to the three default input/output (I/O) streams that are
automatically available when a program runs.

g
• These streams provide a way for the program to interact with the external

or
environment, such as the user's console or other programs. The three standard files

s.
are: te
Types of Standard Files
da

Standard Input (stdin)


p

This is the default input stream, typically connected to the user's keyboard. It allows the
uu

program to receive input from the user. In Python, the input() function reads data from
stdin.
an

• Represents the source of input for the program, typically the keyboard. Accessed
w
w

using sys.stdin.
w

• Used to read data provided by the user or another program.

Standard Output (stdout)

This is the default output stream, usually connected to the user's console or terminal it allows
the program to display output to the user In Python, the print() function writes data to
stdout

✓ Represents the destination for output from the program, typically the console

✓ Accessed using sys.stdout or the print() function.

✓ Used to display information to the user or another program

Standard Error (stderr)


68 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
This is a separate output stream specifically for error messages and diagnostic information. It
is also typically connected to the user's console, but it can be redirected separately from
stdout. In Python, you can write to stderr using the sys.stderr object.

• Represents the destination for error messages and diagnostics.

• Accessed using sys.stderr

• Used to output error information separately from regular output.

Working with Standard Files

These standard files are file-like objects, meaning they can be read from and written to using
methods similar to regular file operations.

Ex:

g
or
import sys

#Reading from standard input


s.
te
input_data= sys.stdin.readline()
da

print("You entered:", input_data) #Writing to standard output


p
uu

sys.stdout.write("This is standard output'n") #Writing to standard error


an

sys.stderr.write("This is an error message\n")


w

Q. Command Line Arguments


w
w

Python Command Line Arguments provides a convenient way to accept some information
at the command line while running the program. We usually pass these values along with
the name of the Python script.

Syntax: python program_name.py arg1 arg2 arg3...

• python: The keyword to invoke the Python interpreter.

• program_name.py: The name of your Python program file.

• arg1, arg2, arg3, and so on: The command-line arguments you want to pass to the
program. These arguments are separated by spaces.

Python provides various ways of dealing with these types of arguments. The three most
common are:

69 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


1. Using sys.argv

2. Using getopt module

3. Using argparse module

a) Using sys.argv:

The simplest way to handle command line arguments is by using the sys module's argy. The
argy is a list in Python, which contains the command-line-arguments pass argument to
python script. The first argument, argv[0], is always the script name itself.
Ex

import sys

g
print("Script Name is:", sys.argv[0])

or
print("Arguments are:", sys.argv[1:])

s.
te
Command Line Interface:
da

python generate random.py 1 100 5


p

Output:
uu

Script Name is generate_random.py


an

Arguments are:[1,100.5]
w

b) Using getopt Module:


w

The getopt module is a more powerful tool for parsing command line arguments. It offers
w

functions like getopt() and gnu_getopt() that parse argument lists and return a tuple
containing two lists. The first list contains simple options, and the second list contains
arguments that are associated with some option. Here's how you can use it:
Ex
import sys import getopt

try:
opts, args getopt.getopt(sys.argv[1], "ho:", ["help", "output="])

except getopt.GetoptError as err


print(err) # Process options
for opt, arg in opts:
if opt in("-h", "--help"):
print("Help Needed")
elif opt in ("-o", "-output"):
print("Arguments Passed with-o Option:-",arg)

70 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Command Line Interface:
python CML.py-h

Output: Help Needed

Command Line Interface:

python CML.py -0 5

Output:

Arguments Passed with -o Option:-5

c) Using Argparse Module :

g
Argparse is the recommended command-line parsing module in Python's standard library. It's

or
the in-built solution for command line arguments. It creates a parser that reads command-
line arguments, where you can specify what options the command-line of your script should
have. Ex
s.
te
import argparse
da

parser =argparse.ArgumentParser()
p
uu

parser.add_argument("--arguments", help="insert argg")


an

args =parser.parse_args()
w

print(args.arguments.lower())
w

Command Line Interface:


w

python Lower py-arguments Hi, Himanshu

Output: hi,himanshu

Q. File System

In python, the file system contains the files and directories. To handle these files and

directories python supports "os" module. Python has the "os" module, which provides us

with many useful methods to work with directories (and files as well).

The os module provides us the methods that are involved in file processing operations and

71 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


directory processing like renaming, deleting, get current directory, changing directory etc.

Renaming the file rename():

The os module provides us the rename() method which is used to rename the specified file
to a new name.

Syntax: os.rename ("current-name", "new-name")

Ex:

import os;

#rename file2.txt to file3.txt

os.rename("file2.txt","file3.txt")

g
or
Removing the file - remove():

s.
The os module provides us the remove() method which is used to remove the specified file.
te
Syntax: os.remove("file-name")
da

Ex:
p
uu

import os:
an

#deleting the file named file3.txt


w

os.remove("file3.txt")
w

Creating the new directory - mkdir()


w

The mkdir() method is used to create the directories in the current working directory

Syntax: os.mkdir("directory-name")

Ex: import os;

#creating a new directory with the name new

os.mkdir("dirnew")

Changing the current working directory-chdir()

The chdir() method is used to change the current working directory to a specified directory

72 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Syntax: os.chdir("new-directory")

Ex:

import os;

#changing the current working directory to new

os.chdir("dir2")

Get current working directory - getpwd():

This method returns the current working directory

Syntax. os.getcwd()

g
Ex:

or
import os;

s.
te
#printing the current working directory
da

print(os.getewd())
p

Deleting directory - rmdir(): The rmdir() method is used to delete the specified directory.
uu

Syntax. os.rmdir("directory name")


an

Ex:
w
w

import os;
w

#removing the new directory

os.rmdir("dir2")

List Directories and Files-listdir(): All files and sub directories inside a directory can be known
using the listdir() method. This method takes in a path and returns a list of sub directories
and files in that path. If no path is specified, it returns from the current working directory.
Syntax: os.listdir(["path"])

Ex:

import os;

#list of files and directories in current working directory

73 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


print(os.listdir()) #list of files and directories in specified path

print(os.listdir("D:\\"))

Core Operations

• Opening Files: The open() function is used to open files. It accepts two arguments:
the file path and the mode of operation ('r' for read, 'w' for write, 'a' for append, 'r+'
for read and write).

• Reading Files: read() reads the entire file, readline() reads a single line, and readlines()
reads all lines into a list.

• Writing to Files: write() writes a string to the file.

• Closing Files: It's crucial to close files after use, which can be done using file.close() or

g
the with statement, which automatically closes the file.

or
s.
Q. File Execution te
Python is a well-known high-level programming language. The Python script is a file
da
containing Python-written code. The file containing Python script has the extension py' or
can also have the extension pyw if it is being run on a Windows 10 machine or various
techniques for executing a Python script...
p
uu

Running Python Scripts in Terminal:


an

1. Open a Terminal: If you're using a Linux or macOS system, you can usually find a terminal
application in your applications or through a system search. Commonly used open terminal
w

python include the GNOME Terminal, Konsole, and macOS's Terminal.


w

On Windows, you can use the Command Prompt or PowerShell. You can find the
w

Command Prompt by searching for "cmd" or "Command Prompt" in the Start menu, while
PowerShell can be found similarly.

2. Navigate to Your Script's Directory: Use the ed (change directory) command to navigate
to the directory where your Python script is located. For example, if your script is in a folder
called "my_python_scripts," you can navigate to it like this while learning how to run a
python script in terminal
cd path/to/my_python_scripts
3. Run the Python Script: To run a Python script, use the Python command, followed by
the name of your script. For instance: python my_script.py

To run a python script in Linux

If you're using Linux, running a Python script in Python 3 is quite straightforward. First, open

74 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


your terminal. Navigate to the directory where your script is located using the ed command.

For example:

ed path/to/your/script

Once you're in the correct directory, type the following command: python3 script_name.py
script name.py can be replaced with your file name.

Running Python Scripts as Executables

You can also run Python scripts as executables on Unix-like systems. First, add the shebang
line at the top of your script:

#!/usr/bin/env python3

g
Then, with the following command, you can make the script executable: chmod +x

or
script_name.py Now simply, type the below command to run your script directly.

/script_name.py
s.
te
How to Run Python on Windows
da

On Windows, Command Prompt can be used to run the Python scripts with ease. Just open
p

Command Prompt and use the cd command to go to your script's directory:


uu

ed path\to\your script
an

Then, run your script with: python script_name.py


w

Ensure Python is added to your system PATH to run it from any directory
w
w

Running Python command line argument

Sometimes, you'll need to run scripts with command line arguments. Here's how you can do
it. In your script, you can handle arguments using the sys module:

import sys

print(sys.argv)

To run the script with arguments, use the terminal :python script_name.py arg1 arg2
Replace argl and arg2 with your actual arguments.

Q. Exceptions in Python

In Python, an exception is an event that occurs during the execution of a program and
75 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
disrupts the normal flow of the program. It represents an error or an exception condition
that the program encounters and cannot handle by itself.

When an exception occurs, it is "raised" or "thrown" by the Python interpreter The exception
then propagates up the call stack, searching for an exception handler that can catch and
handle the exception. If no suitable exception handler is found, the program terminates, and
an error message is displayed.

Ex:

try:

result 10/0#Raises ZeroDivisionError

except ZeroDivisionError

g
print("Error Division by zero!")

or
In this example, the code within the try block raises a ZeroDivisionError exception when

s.
attempting to divide by zero. The exception is caught by the except block, and the specified
te
error message is printed, allowing the program to continue execution instead of abruptly
terminating. In this example, the code within the try block raises a ZeroDivisionError
da

exception when attempting to divide by zero. The exception is caught by the except block,
and the specified error message is printed, allowing the program to continue execution
p

instead of abruptly terminating.


uu

Different Types of Exceptions in Python:


an

1. SyntaxError: When the interpreter comes across a syntactic problem in the code, such as a
w

misspelled word, a missing colon, or an unbalanced pair of parentheses, this exception is


w

raised.
w

2. TypeError: When an operation or function is done to an object of the incorrect type, such
as by adding a string to an integer, an exception is thrown.

3. NameError: When a variable or function name cannot be found in the current scope,
the exception NameError is thrown.

4. IndexError: This exception is thrown when a list, tuple, or other sequence type's
index is outside of bounds.

5. KeyError: When a key cannot be found in a dictionary, this exception is thrown.


6. ValueError: This exception is thrown when an invalid argument or input is passed to a
function or method. An example would be trying to convert a string to an integer when the
string does not represent a valid integer.

7. AttributeError: When an attribute or method is not present on an object, such as

76 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


when attempting to access a non-existent attribute of a class instance, the exception
AttributeError is thrown.

8. IOError: This exception is thrown if an input/output error occurs during an I/O


operation, such as reading or writing to a file.

9. ZeroDivisionError: This exception is thrown whenever a division by zero is


attempted.

10. ImportError: This exception is thrown whenever a module cannot be loaded or found
by an import statement.

Q. Types of Exceptions

There are two types of exceptions in Python. Built-in Exceptions

g
User-Defined Exceptions Types of Exceptions in Python

or
s.
te
da

Built-in Python Exceptions


p
uu

Built-in exceptions are the standard exceptions defined in Python. These exceptions are
raised wher the program encounters an illegal operation like semantic errors.
an

These built-in exceptions are generated either by the interpreter or the built-in functions of
w

Python The interpreter returns a string indicating the error code and the related information
whenever an exception is raised.
w
w

Here is the list of default Python exceptions with descriptions:

1. Assertion Error: raised when the assert statement fails.

2. EOFError: raised when the input() function meets the end-of-file condition. 3.
AttributeError: raised when the attribute assignment or reference fails.

4. TabError: raised when the indentations consist of inconsistent tabs or spaces.

5. ImportError: raised when importing the module fails.


6. IndexError: occurs when the index of a sequence is out of range

7. RuntimeError: occurs when an error does not fall into any category.

8. NameError: raised when a variable is not found in the local or global scope.

77 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


9. MemoryError: raised when programs run out of memory.

10. ValueError: occurs when the operation or function receives an argument with the right
type but the wrong value.

11. ZeroDivision Error: raised when you divide a value or variable with zero.

12. SyntaxError: raised by the parser when the Python syntax is wrong.

13. IndentationError: occurs when there is a wrong indentation.

14. SystemError: raised when the interpreter detects an internal error.

Ex: FileNotFoundError

g
This exception is raised when a file or directory is requested, but the specified file or

or
directory does not exist. When a file that should be read, accessed, or retrieved doesn't exist,
Python throws the FileNotFoundError exception.

s.
te
#Python program for FileNotFoundError
da

try:
p

with open(" myfile.txt") as f:


uu

contents =f.read()
an

except FileNotFoundError as e:
w

print(" A file not found error occurred: ", e)


w
w

Output :A file not found error occurred. [Errno 2] No such file or directory: myfile.txt'

User-Defined Exceptions: A user defined exception in Python is an exception that is


constructed by the user or programmer to represent a specific error condition or exceptional
situation in a program. It is also known as a custom exception.
Python offers a wide range of standard built-in exceptions to handle common errors.
Sometimes, there may be situations where built-in exceptions are not sufficient to handle the
different exceptions that occur in the application program.
In this situation, users may need to define their own custom exceptions to handle specific
errors or to add more context to error handling.

For example, if the user wants to withdraw greater than its balance from the ATM machine,
it leads to the exception. Any standard inbuilt exception cannot handle such a kind of
exception.

78 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


In this case, the user can define its own custom exception that will occur when someone will
want to attempt to withdraw the amount greater than its balance. The exception handler in
this case may display a customize message that you cannot withdraw money greater than
the account balance.

Syntax:

class user_defined_exception(Exception):

#Constructor

def__ init __(self, args)

self.args = args

#Additional methods and attributes can be added here

g
Ex :

or
#Create a user defined exception class that inherits from Exception class.

Class MyException(Exception):
s.
te
pass
da

try:
p
uu

raise MyException("My exception") #Exception value stored in m.


an

except MyException as m:
w

print(m)
w

Output: My exception
w

Handling Multiple User-Defined Exceptions: Python allows handling multiple user-defined

exceptions using multiple except blocks. By specifying different exception classes in each
except block, we can handle different types of exceptions separately. This enables
developers to implement specific error-handling logic based on the type of exception raised.
Benefits of Using User-Defined Exceptions

• Improved Code Readability: User-defined exceptions provide a clear indication of


the specific error conditions that can occur in the code. By using descriptive names
for exceptions, developers can easily understand the purpose and context of the
exception.

• Enhanced Error Handling: User-defined exceptions allow developers to handle errors


in a more granular and specific manner. By defining custom exception classes,
79 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
developers can catch and handle different types of errors separately, leading to more
effective error handling and debugging.

• Code Reusability: User-defined exceptions can be reused across multiple projects or


modules, promoting code reusability. By defining common exception classes,
developers can ensure consistent error-handling practices throughout their codebase.

Q. Exception Handling in Python (OR) Detecting and Handling Exceptions

Exceptions can be detected by incorporating them as part of a try statement. Any code suite
of a try statement will be monitored for exceptions.

Exception handling is a technique in Python for dealing with errors that occur during
program execution. It entails spotting potential error situations, responding appropriately to
exceptions when they arise, and identifying possible error conditions. Using the try and
except keywords, Python provides a structured approach to exception handling.

g
or
s.
te
p da
uu
an

Try and Except Statement-Catching Exceptions: Try and except statements are used to catch
w

and handle exceptions in Python. Statements that can raise exceptions are wrapped inside
w

the try block and the statements that handle the exception are written inside except block.
w

Ex:
a=[1,2, 3]
try:

print ("Second element = %d" %(a[1]))

print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

Output: Second element = 2

An error occurred

80 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


In the above example, the statements that can cause the error are placed inside the try
statement (second print statement in our case). The second print statement tries to access the
fourth element of the list which is not there and this throws an exception. This exception is
then caught by the except statement.

Catching Specific Exception

A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed. For example, we can add
IndexError in the above code.
Syntax
try:

#statement(s)

except IndexError:

g
or
#statement(s)

except ValueError:
s.
te
# statement(s)
da

Ex :def fun(a):
p
uu

if a <4 :
an

b=a/(a-3)
w

print("Value of b =", b)
w

try:
w

fun(3)

fun(5)

except ZeroDivisionError:

print("ZeroDivisionError Occurred and Handled")

except NameError:

print("NameError Occurred and Handled") #Output: ZeroDivisionError Occurred and

Handled

81 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Try with Else Clause: In Python, you can also use the else clause on the try-except block
which must be present after all the except clauses. The code enters the else block only if the
try clause does not raise an exception.

Ex

def AbyB(a, b):

try:

c=((a+b)/(a-b))

except ZeroDivisionError:

print ("a/b result in 0")

g
else:

or
print (c)

s.
te
AbyB(2.0, 3.0)
da

AbyB(3.0, 3.0)
p

Output: -5.0
uu

a/b result in 0
an

Finally Keyword in Python: Python provides a keyword finally, which is always executed
w

after the try and except blocks. The final block always executes after the normal termination
w

of the try block or after the try block terminates due to some exception. The code within the
finally block is always executed.
w

Syntax:

try:

#Some Code.....

except:

#optional block
#Handling of exception (if required)

else:

#execute if no exception
82 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
finally:

#Some code…………. (always executed)

Ex :
try:

k=5//0

print(k)

except ZeroDivisionError:

print("Can't divide by zero") finally:

print('This is always executed')

g
or
Output:

Can't divide by zero This is always executed


s.
te
Q. Context Management
da

A context manager in Python is a design pattern that facilitates the allocation and
p

deallocation of resources, ensuring that certain tasks are performed before and after a
uu

section of code. The most common use case is file handling, where a file needs to be
opened, then eventually closed, whether the operations in between were successful or not.
an

• Context managers are useful for managing files, network connections, database
w

connections, and any other resources that require setup and cleanup.
w

• They promote cleaner, more readable, and more robust code by ensuring resources
w

are properly handled.

In Python, you can use two general approaches to deal with resource management. You can
wrap your code in:

1. A try__ finally construct

83 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


2. A with construct

The with Statement Approach

The Python with statement creates a runtime context that allows you to run a group of
statements under the control of a context manager. Compared to traditional try finally
constructs, the with statement can make your code clearer, safer, and reusable. Many classes
in the standard library support the with statement. A classic example of this is open(), which
allows you to work with file objects using with.

syntax:

with expression as target_var:

do_something(target_var) with open('file.txt', 'r') as file:

g
or
ex :

with open (‘file.txt’,’r’) as file:


s.
te
da
content = file.read()

Here, after executing the block of code inside the 'with statement, the file is automatically
p

closed, even if an exception occurs within the block.


uu

Context management protocol consists of two special methods:


an

1. .__enter__() is called by the with statement to enter the runtime context.


w
w

2. .__exit__() is called when the execution leaves the with code block.
w

Here's how the with statement proceeds when Python runs into it.

1. Call expression to obtain a context manager.

2. Store the context manager's .__enter__() and.__ exit__() methods for later use.

3. Call .__enter__() on the context manager and bind its return value to target_var if
provided.

4. Execute the with code block.

5. Call.__exit__() on the context manager when the with code block finishes.

Understanding Context Managers:

84 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


1 How They Work:

At the heart of a context manager are two magic methods:.__enter__ () and .__exit__ ()

• .__enter__() is called when the ‘with’ block is entered. It can return an object that
will be used within the block.

• .__exit__() is called when the ‘with’ block is exited. It handles cleanup operations,
like closing a file or releasing a lock.

2 Creating Custom Context Managers:

You can create your own context manager by defining a class with .__enter__() and
.__exit__()
methods:

g
Ex :

or
class MyContextManager:

s.
te
def__enter__ (self):
da

#Initialization or resource allocation


p

return self
uu

def__exit (self, exc_type, exc_value, traceback):


an

#Cleanup or resource deallocation


w

Pass
w
w

3. The contextlib Module:

Python's standard library provides a module named contextlib which offers utilities to create
context managers without always defining a new class. The @contextmanager decorator
allows you to build a context manager using a generator function: Ex:

from contextlib import contextmanager

@contextmanager

def managed_resource():

resource =allocate_resource()

yield resource

85 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


resource.deallocate()

Context managers in Python provide a structured and safe way to manage resources,
ensuring that initialization and cleanup tasks are reliably executed. By leveraging context
managers, developers can write cleaner, more maintainable, and error-resistant code,
especially when dealing with external resources or operations that require precise setup and
teardown procedures.

Benefits of Python Context Manager

• Concise Syntax: It removes the need for explicit setup and takedown code,

simplifying the code.

g
or
• Automatic Resource Handling: Context managers automatically manage resource

s.
allocation and deallocation, ensuring that resources like files, network connections,
te
and appropriate releasing of locks after usage. This is known as automatic resource
da

handling.
p
uu

• Exception Safety: The context manager ensures that it properly cleans up the
resources, preventing leaks even in the case of an error within a block.
an

• Less Boilerplate Code: Context managers simplify and ease the maintenance of the
codebase by removing the boilerplate code required for resource management.
w
w

Q. Exceptions as Strings
w

• Before Python 1.5, exceptions were represented as strings. While this approach was
simple, a lacked the structure and flexibility of classes.

• In Python 1.5, standard exceptions were transitioned to classes, offering better


organization and extensibility. Although string exceptions are no longer
recommended, understanding their usage is helpful for working with older code or
recognizing them when encountered.

• String exceptions were raised using the raise statement followed by a string literal or
variable containing the error message.

Ex:

try:

86 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


#Code that might raise an exception

x=10/0

except "division by zero" :

print("Caught a string exception: division by zero")

String exceptions could be caught using the except clause with the string literal matching the
exception.

Ex :

try:

g
#Code that might raise an exception

or
raise "File not found"

except "File not found":


s.
te
da
print("Caught a string exception: File not found")
p

It's important to note that this approach is outdated and using class-based exceptions is now
the standard practice in Python.
uu

Q. Raising Exceptions
an

The raise keyword is used to raise an exception. You can define what kind of error to raise,
w

and the text to print to the user.except is a keyword (case-sensitive) in python, it is used to
w

raise an Exception/Error with a customized message and stops the execution of the
programs.
w

It is very useful when you want to work with the input validations. For example if you are
working with the positive numbers and someone inputs a negative number, in this case, we
can raise an error and stop the program's execution.

Syntax:

if test_condition:

raise Exception(Message)

Ex:

string = "Hello"

87 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


if string =="Hello" or string== "Hi" or string =="Bye":

raise Exception("This word is not allowed")

Output:

Exception: This word is not allowed

Raising Built-in Exceptions

If you have a piece of code where along with exception handling you have put in place
some conditional statements to validate input etc, then in case of the conditions failing we
can either just print a message or simple raise an exception which can then get handled by
the common exception handling mechanism.

Syntax:

g
raise Exception("This is a general exception")

or
Ex:

s.
te
def divide(a, b):
if b==0:
da

raise ValueError("Cannot divide by zero")


p

return a/b
uu

try:
an

result divide(10, 0)
w
w

except ValueError as e:
w

print(e)

Output: Cannot divide by zero

Custom Exceptions:

Custom exceptions is useful for handling specific error conditions that are unique to your
application, providing more precise error reporting and control.

To create a custom exception in Python, you define a new class that inherits from the built-
in Exception class or any other appropriate built-in exception class. This custom exception
class can have additional attributes and methods to provide more detailed context about the
error condition.

Ex:

88 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


class InvalidAgeError(Exception):

def__init__ (self, age, message="Age must be between 18 and 100"):

self.age = age

self.message== message

super(). init (self.message)

def set_age(age):

if age 18 or age > 100:

raise InvalidAgeError(age)

g
print(f"Age is set to {age}")

or
s.
try: te
set_age(150)
da

except InvalidAgeError as e:
p

print(f"Invalid age: {e.age}.{e.message}")


uu

Output: Invalid age: 150. Age must be between 18 and 100


an

Advantages of the raise keyword


w
w

• It helps us raise error exceptions when we may run into situations where execution
w

can't proceed

• It helps us raise error in Python that is caught. Raise allows us to throw one exception

at any time.

• It is useful when we want to work with input validations.

Q. Assertions

There are two basic techniques to handle errors and unexpected issues while coding in
Python: assert statements and exceptions.

The assert statement is used to determine whether or not a given condition is true. If the

89 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


condition not met, an AssertionError is thrown. Assert statements are mostly used for
debugging and a usually deactivated in production code.
Exceptions, on the other hand, are used to handle runtime problems and unexpected
circumstances When an error occurs, an exception is thrown and may be captured and
handled using try-except blocks. Exceptions are used in both the creation and execution of
code to gracefully handle failures and ensure that the program runs even when an error
occurs.

Assertions in Python

Assertions in Python are statements that assert or assume a condition to be true. If the
condition turns out to be false, Python raises an AssertionError exception. They are used to
detect programming errors that should never occur if the code is correct.

Syntax:

g
assert <condition>

or
assert <condition>, <error message>

s.
te
1) assert statement has a condition and if the condition is not satisfied the program will stop
and give AssertionError
da

2) assert statement can also have a condition and a optional error message. If the condition
p

is not satisfied assert stops the program and gives AssertionError along with the error
uu

message.
Flowchart :
an
w
w
w

Ex 1: Using assert without Error Message

def avg(marks):

assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark 1:",avg(mark 1))

Output: AssertionError

We got an error as we passed an empty list mark1 to assert statement, the condition became

90 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


false and assert stops the program and give AssertionError.

Now let's pass another list which will satisfy the assert condition and see what will be our
output.

Ex 2: Using assert with error message

def avg(marks):
assert len(marks)!=0,"List is empty."
return sum(marks)/len(marks)
mark2= [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark 1:",avg(mark1))

output :Average of mark2: 78.0

g
AssertionError List is empty.

or
We passed a non-empty list mark2 and also an empty list mark1 to the avg() function and

s.
we got output for mark2 list but after that we got an error AssertionError: List is empty. The
te
assert condition was satisfied by the mark2 list and program to continue to run. However,
mark! doesn't satisfy the condition and gives an AssertionError.
da

Use Python Assert Statement


p
uu

In Python, the assert statement is a potent debugging tool that can assist in identifying
mistakes and ensuring that your code is operating as intended. Here are several justifications
an

for using assert.


w

1. Debugging: Assumptions made by your code can be verified with the assert statement.
You may rapidly find mistakes and debug your program by placing assert statements
w

throughout your code.


w

2. Documentation: The use of assert statements in your code might act as documentation.
Assert statements make it simpler for others to understand and work with your code since
they explicitly describe the assumptions that your code is making.

3. Testing: In order to ensure that certain requirements are met, assert statements are
frequently used in unit testing. You can make sure that your code is working properly and
that any changes you make don't damage current functionality by incorporating assert
statements in your tests.

4. Security: You can use assert to check that program inputs comply with requirements and
validate them. By doing so, security flaws like buffer overflows and SQL injection attacks
may be avoided.
Q. Standard Exceptions

91 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Standard Exceptions in Python

In Python versions 1.5 and later, the standard exceptions are Python classes, and a few new

standard exceptions have been added. Python supports various built-in exceptions, the

commonly used exceptions are

• NameError: It occurs when a name is not found.i.e attempt to access an undeclared

variable

Ex:

g
a=5

or
c=a+b

s.
te
print("Sum =",c)
da

Output:
p

Traceback (most recent call last):


uu

File "expdemo.py", line 2, in


an

c=a+b
w

NameError: name 'b' is not defined


w
w

• ZeroDivisionError: Occurs when a number is divided by zero.

Ex:

a=5

b=0

print(a/b)

Output:

Traceback (most recent call last):


File "expdemo.py", line 3, in
print(a/b)
ZeroDivisionError: division by zero
92 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
• ValueError: Occurs when an inappropriate value assigned to variable.

Ex:

a=int(input("Enter a number: "))


b=int(input("Enter a number: "))

print("Sum=”+b)

Output:

Enter a number: 23

Enter a number :abc

g
Traceback (most recent call last):

or
File "expdemo.py", line 2, in

s.
te
b-int(input("Enter a number: "))
da

ValueError: invalid literal for int() with base 10: "abc"


p

• Index Error: Occurs when we request for an out-of-range index for sequence
uu

Ex:
an

Is=['e','java', 'python']
w

print("list item is ",ls[5])


w
w

Output:

Traceback (most recent call last):

File "expdemo.py", line 2, in

print("list item is:",ls[5])

IndexError: list index out of range.

• KeyError: Occurs when we request for a non-existent dictionary key

Ex: dic={"name":"Madhu","location":"Hyd")

print("The age is:",dic["age"])

93 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Output:

Traceback (most recent call last):

File "expdemo.py", line 2, in

print("The age is:",dic["age"])

KeyError: 'age'

• IOError: Occurs when we request for a non-existent input/output file

Ex:

F=-open("exam.py")

g
print(fn)

or
s.
Output: te
Traceback (most recent call last);
File "expdemo.py", line 1, in
da

fn-open("exam.py")
p
uu

FileNotFoundError: [IOError] No such file or directory: 'exam.py’


an

Q. Creating Exceptions
w

To create custom exceptions, define a Python class that inherits from the Exception class. The
Exception class offers base functionality you'll need to handle exceptions, and you can
w

customize it to add features based on your specific needs.


w

When creating custom exception classes, keep them simple while including necessary
attributes for storing error information. Exception handlers can then access these attributes to
handle errors appropriately.

Steps to Create a Custom Exception:

• Define the Exception Class: Create a new class that inherits from the built-in
"Exception" class or any other appropriate base class. This new class will serve as
your custom exception.

Ex:

class CustomError(Exception):

94 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


"""Base class for other exceptions"“”

pass

class SpecificError(CustomError):

"""Specific exception type"""

def__init__(self, message):
self.message= message
super(). _init__ (self.message)

• Initialize the Exception (Optional): Implement the" init "method to initialize any
attributes or provide custom error messages. This allows you to pass specific
information about the error when raising the exception.

g
class ValueError(Exception):

or
def__ init__(self, message="Invalid value"):

s.
te
self.message =message
da

super().__init__(self.message)
p

• Raise the Exception: Once you have defined a custom exception, you can raise it in
uu

your code to signify specific error conditions. Raising user-defined exceptions


involves using the raise statement, which can be done with or without custom
an

messages and attributes.


w

Syntax :
w

raise ExceptionType(args)
w

Ex :

def process data(value):

if not isinstance(value, int):

raise ValueError("Input must be an integer")

return value *2

• Handle the Exception:

Handling user-defined exceptions in Python refers to using "try-except" blocks to catch and

95 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


respond to the specific conditions that your custom exceptions represent. This allows your
program to handle errors gracefully and continue running or to take specific actions based
on the type of exception raised.

Ex:

try:

result =process_data("hello")

except ValueError as e:
print(f"Error: (e}")
else:
print(f"Result: (result)")
Ex :
class InvalidAgeError(Exception):

g
or
def__ init__ (self, age, message "Age must be between 18 and 100"):

self.age = age
s.
te
self.message= message
da

super().__ init__ (self.message)


def __str__ (self):
p

return f" {self.message}provided age:{self.age}"


uu

def set_age(age):
an

if age 18 or age > 100:


w

raise InvalidAgeError(age)
w
w

print(f"Age is set to {age}")

try:

set _age(150)

except InvalidAgeError as e:

print(f"Invalid age: (c.age) (e.message)")

Output Invalid age: 150. Age must be between 18 and 100

Q. Exceptions and the sys Module

The sys module in Python contains several methods and variables for manipulating various
aspects of the Python runtime environment. It helps you work with the interpreter since it
96 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
gives you access to variables and functions that work closely with it.

Important Variables In The SYS Module

Version: It helps you understand the version of Python being in use.

Ex:

import sys
sys.version

Output :’3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21)

sys.argv:

In Python, this includes a list of arguments (command prompt) supplied to the script. If you

g
write len(sys.argv), you'll get a count of how many arguments there are. sys.argv is used by

or
people who work with command-line arguments. The name of the script is referred to as
Sys.argv[0]

s.
te
Ex:
da

import sys
print(sys.argv[0])
p

print('Number of arguments present=', len(sys.argv))


uu

print('Total argument list:', str(sys.argv))


an

Output:
w

sys.py
w

Number of arguments present = 1


w

Total argument list: ['sys.py']

sys.path:

This function displays the current system's python path. It's an environmental variable that
contains the search path for all of the python modules.

Ex:

import sys
sys.path

Output: [", "C:\\Python39\\Lib\\idlelib']

97 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


sys.maxsize: This maxsize function returns the variable's greatest integer

Ex :import sys

sys.maxsize

Output: 9223372036854775807

Important Functions In The SYS Module

sys.exit(): The program will exit the python console or the command prompt. It is usually
used to exit the application if an exception is thrown securely.
Ex :
import sys
def is_even(list):
if any (i%21 for i in list):

g
print("ERROR. Odd one is present in the even list! ")

or
sys.exit()

s.
else:
print("Pure Even List")
te
list= [2,4,5,6,8,10]
is_even(list)
da

is_ even(list)
p

Output: ERROR: Odd one is present in the even list!


uu

2. sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings
an

in the Python environment.


w

Ex:
w

import sys
w

sys.setdefaultencoding('UTF8')

3. sys.getsizeof():

After using this function, the size of an object in bytes is returned. Any object can be used as
an object.

Ex: import sys

i=3

print(sys.getsizeof(i))

Output: 28

98 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Input And Output Using SYS

Variables in the sys modules provide for good control of input and output. We can even
send input and output to different devices using these variables. We can use two variables to
do this, which are listed below.

1. stdin: This stdin can be used to take input from the command line directly. This stdin
method is used for taking standard input. It uses the input() function internally. It also adds a
\n that is a new line at the end of each sentence. Let's understand this with an example given
below

Ex:

import sys

for words in sys.stdin:

g
or
if 'quit' words.rstrip():

break
s.
te
print(f'Input (words)")
da

print("Exit!!")
p
uu

Output:
an

Hello
w

Input: Hello
w

Bye
w

Input: Bye

quit

Exit

2. stdout:

The interpreter's standard output stream in Python is analogous to this built-in file object.
The stdout command sends output to the screen console. The output that comes out using
the print statement, an expression statement, or even a prompt direct for input, might take
many different forms. Streams are set to text mode by default. Whenever a print function is
used in the code, it is written first to sys.stdout, then to the screen. Let's understand this in a
better way from the example that is given below:
99 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Ex

import sys

sys.stdout.write('Learn_To_Code')

Output:

Learn_ To_Code

Q. Modules and Files

In Python, modules are files containing Python definitions and statements, while files are used
to store data or code. Modules facilitate code organization and reusability, and files handle
data persistence.

g
or
Modules: According to the formal definition of Python modules, they are a Python file
containing statements, definitions, Python code, classes, functions, and variables. They are

s.
the files with the py extension. A Python module can also include runnable code.
te
da
When we group related code into a module, it makes it easier to understand and use. Also,
the code is more logically organized. A common real-life example is a music store with many
sections containing different types of songs and music.
p
uu

Features of Modules.
an

• Allows code reusability


w

• Provides flexibility in organizing code logically and segments a larger problem into
w

small manageable files.


w

diagram

Create a python Module


You can create a Python module by writing the desired code and saving the file using the py
extension.

Ex: Creating a module named "mymath" #mymath.py

def add(a, b):

"""Return the sum of two numbers.""" return a + b

def subtract(a, b):

Return the difference between two numbers."" return a - b


100 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Types of Modules in Python

There are two types of Python modules:

1. In-built modules in Python

2. User-Defined Modules in Python

1. In-built Modules in Python

The Python built-in modules come with a Python standard library, offering a range of
functionalities. So, you don't need to install these modules separately, as they are available
in Python by default. There are several in-built Python modules, such as sys, math, os,
random, etc.

g
or
s.
te
p da
uu
an
w
w
w

101 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Built-In modules like:

math sys OS

random and many more.

2. User-defined Modules in Python

Users create these modules to make their code more organized, modular, and reusable. These
are defined in a different py file, so you must import and use them in your Python scripts.

There are a few other types of Python modules, such as package modules, third-party
modules, and extension modules.

Variables in Python Modules

g
We have already discussed that modules contain functions and classes. But apart from

or
functions and classes, modules in Python can also contain variables in them. Variables like

s.
tuples, lists, dictionaries, objects, etc. te
Example
da

#This is variables module


p

## this is a function in module def factorial(n):


uu

if n1||n=0:
an

return 1 else:
w
w

return n factorial(n-1)
w

## this is dictionary in module power = {

1:1,

2:4,

102 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


3:9,
4:16.

5:25.

1 ##This is a list in the module alphabets [a,b,c,d,e,f,g,h]

Q. Namespaces

In Python, a namespace is a collection of names, which can be variables, functions, classes,


or modules. Namespaces provide a way to organize and manage the names in a Python
program, ensuring that each name is unique and can be accessed correctly.

Types of Namespaces in Python

g
Global Namespace: This is the top-level namespace that contains all the names defined at

or
the module level.

s.
Local Namespace: This is the namespace that contains the names defined within a function
te
or a class.
da

Built-in Namespace: This is the namespace that contains the built-in functions, types, and
constants provided by the Python interpreter.
p
uu

Accessing Namespaces
an

In Python, you can access the names in a namespace using the dot notation. For example, to
access a variable x in the global namespace, you would use x, while to access a function
w

my_function in a module my_module, you would use my_module.my_function.


w

Ex
w

## Example of accessing namespaces x=10## Global namespace

def my function():

y20 ## Local namespace

print(x) ## Access global namespace print(y) ## Access local namespace my_function()

103 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Namespace Hierarchy: Python's namespace hierarchy follows a specific structure, where the
built-in namespace is the top-level namespace, followed by the global namespace, and then
the local namespaces. This hierarchy determines how names are resolved when they are
referenced in a Python program.

Diagram

By understanding the concept of namespaces and how they work in Python, you can write
more organized and maintainable code, and avoid naming conflicts that can lead to bugs
and errors.
Working with Namespaces in Python

In Python, you can manipulate namespaces using various built-in functions and keywords,
such as:

g
a) globals(): Returns a dictionary of the names in the global namespace

or
b) locals(): Returns a dictionary of the names in the current local namespace.

s.
c) dir(): Returns a list of names in the namespace of an object.
d) import statement. Brings names from a module into the current namespace. e) as
te
keyword: Allows you to assign a different name to an imported object. f)_name_variable:
da
Provides information about the current namespace.

Ex :
p
uu

## Example of namespace manipulation import math as m


an

print(globals()) ### Access global namespace print(locals()) ## Access local namespace


w

print(dir(m)) ## Access namespace of the math module print(name) ## Access the current
w

namespace name
w

Q. Importing Modules

A file is considered as a module in python. To use the module, you have to import it using
the import keyword. The function or variables present inside the file can be used in another
file by importing the module. This functionality is available in other languages, like
typescript, JavaScript, java, ruby, etc.

Importing a Module in Python

The most common way to use a module is by importing it with the import statement. This
allows access to all the functions and variables defined in the module.

104 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex:

import math pie math.pi

print("The value of pi is:", pic)

Output: The value of pi is: 3.141592653589793 Importing Specific Functions

Instead of importing the entire module, we can import only the functions or variables we
need using the from keyword. This makes the code cleaner and avoids unnecessary imports.

Ex

from math import pi print(pi)

g
Output: 3.141592653589793

or
s.
Importing Built-in Modules te
Python provides many built-in modules that can be imported directly without installation.
da
These modules offer ready-to-use functions for various tasks, such as random number
generation, math operations and file handling.
p

Ex
uu

import random
an

#Generate a random number between 1 and 10 res random.randint(1, 10)


w
w

print("Random Number:", res) Output: Random Number: 9 Importing Modules with Aliases
w

To make code more readable and concise, we can assign an alias to a module using the as
keyword. This is especially useful when working with long module names.

105 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex

import math as m

#Use the alias to call a function result m.sqrt(25)

print("Square root of 25:", result) Importing Everything from a Module (*)

Instead of importing specific functions, we can import all functions and variables from a
module using the symbol. This allows direct access to all module contents without prefixing
them with the module name.

Ex.

from math import *

g
print(pi) #Accessing the constant 'pi' print(factorial(6)) # Using the factorial function Output:

or
s.
3.141592653589793 te
720
da

Advantages:
p

It becomes easy to trace back the modules for code check. Easy to use and very
uu

straightforward.
an

If the project is moved to a different path, still the imports will remain the same.
w
w

Q. Importing Module Attributes


w

Python module has its attributes that describes it. Attributes perform some tasks or contain
some information about the module. Some of the important attributes are explained below:

_name_ Attribute:

The name attribute returns the name of the module. By default, the name of the file
(excluding the extension .py) is the value of _name_attribute.

106 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex: Example:_name_Attribute

import math
print(math. name) #’math’

In the same way, it gives the name of your custom module e.g. calc module will return 'calc'.

Ex Example: _name_Attribute import calc print(calc._name)#'calc'

However, this can be modified by assigning different strings to this attribute. Change
hello.py as shown below.

Example: Set name_ def SayHello(name):

print ("Hi ()! How are you?".format(name)) name="SayHello"

g
And check the name attribute now.

or
s.
Example: Set name_ import hello te
print(hello_name) #"Say Hello
da

The value of the_name_ attribute is_main_ on the Python interactive shell and in the
main.py module.
p
uu

Example:_main_ print(name)
an

Example: welcome.py
w

Q. Module Built-in Functions


w

→ OS module:
w

This module has functions to perform many tasks of operating system. mkdir(): We can

create a new directory using mkdir() function from os module.

107 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


import os os.mkdir("d:\\tempdir")

A new directory corresponding to path in string argument in the function will be created. If
we open

D drive in Windows explorer we should notice tempdir folder created.

rmdir(): The rmdir() function in os module removes a specified directory either with
absolute or relative path. However it should not be the current working directory and it
should be empty.

Ex os.rmdir("d:\\temp")

listdir(): The os module has listdir() function which returns list of all files in specified

g
directory.

or
os.listdir("c:\\Users")

s.
te
['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public'] statistics module
da

This module provides following statistical functions:


p

mean() calculate arithmetic mean of numbers in a list Ex :


uu

import statistics statistics.mean([2,5,6,9])


an

Output 5.5
w

median() returns middle value of numeric data in a list. For odd items in list, it returns value
w

at (n + 1) / 2 position. For even values, average of values at n/2 and (n / 2) + 1 positions is


w

returned. Ex

import statistics statistics.median([1,2,3,8,9]) Output :3

108 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


mode(): returns most repeated data point in the list. Ex :

import statistics statistics.mode([2,5,3,2,8,3,9,4,2,5,6])

Output: 2

stdev() calculates standard deviation on given sample in the form of list.

Ex

import statistics statistics.stdev([1,1.5,2,2.5,3,3,5,4,4.5,5]) Output 1.3693063937629153

Time module:

This module has many time related functions.

g
time(): This function returns current system time in ticks. The ticks is number of seconds

or
elapsed after epoch time i.e. 12.00 am, January 1, 1970.

Ex time.time()
s.
te
da
Output 1544348359.1183174

localtime(): This function translates time in ticks in a time tuple notation. Ex tk = time.time()
p
uu

time.localtime(tk) Output :
an

time.struct_time(tm_year = 2018 , tm_mon-12, tm_mday 9, tm_hour = 15 , tm_min = 11 ,


tm_sec=25,
w
w

tm_wday-6, tm_yday-343, t m\ isdst=0)


w

asctime(): This functions readable format of local time Ex

109 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


tk = 1 time.time()

tp = 1 time.localtime(tk) time.asctime(tp)

Output: 'Sun Dec 9 15:11:25 2018'

ctime(): This function returns string representation of system's current time Ex time.ctime()

Output: 'Sun Dec 9 15:17:40 2018"

sleep(): This function halts current program execution for a specified duration in seconds. Ex

time.ctime()

Output: 'Sun Dec 9 15:19:14 2018' Ex time.sleep(20)

g
time.ctime()

or
s.
Output 'Sun Dec 9 15:19:34 2018' sys module: te
This module provides functions and variables used to manipulate different parts of the
da
Python runtime environment.
p

sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings in
the
uu

Python environment. Ex:


an

import sys sys.setdefaultencoding("UTF8") sys.getsizeof():


w
w

After using this function, the size of an object in bytes is returned. Any object can be used as
an
w

object.

110 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex:

import sys i-3 print(sys.getsizeof(i))

Output 28

sys.exit: This causes program to end and return to either Python console or command
prompt. It is used to safely exit from program in case of exception.

Q. Packages

A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required in a
program, that package can be imported and its modules can be put to use.

g
A package is a directory of Python modules that contains an additional init py file, which

or
distinguishes a package from a directory that is supposed to contain multiple Python scripts.

s.
Packages can be nested to multiple depths if each corresponding directory contains its own_
init_.py file.
te
da
Diagram

The file/folder structure should be as shown below:


p
uu

PackageDemo example.py testpackage.py setup.py mypackage


an

init py areafunctions.py mathfunctions.py


w

To Create Package in Python


w

Creating packages in Python allows you to organize your code into reusable and
w

manageable modules. Here's a brief overview of how to create packages:

111 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Create a Directory: Start by creating a directory (folder) for your package. This directory will

serve as the root of your package structure. Add Modules: Within the package directory,
you can add Python files (modules) containing your code. Each module should represent a
distinct functionality or component of your package.

Init File: Include an init py file in the package directory This file can be empty or can contain
an initialization code for your package. It signals to Python that the directory should be
treated as a package.

Subpackages: You can create sub-packages within your package by adding additional
directories containing modules, along with their own init py files.

Importing: To use modules from your package, import them into your Python scripts using
dot notation. For example, if you have a module named modulel py inside a package

g
named mypackage, you would import its function like this: from mypackage.modulel import
greet.

or
s.
Distribution: If you want to distribute your package for others to use, you can create a
setup.py file using Python's setuptools library. This file defines metadata about your package
te
and specifies how it should be installed.
da

Ex:
p

step1:
uu

#mathfunctions.py
an

def average(x,y): val= (x+y)/2 return val


w
w

step2:
w

#areafunctions.py def rectangle(w,h):

area wh return area

step3 : #example.py

from mypackage.areafunctions import rectangle print ("Area", rectangle(10,20)) from


mypackage.mathsfunctions import average

print ("average:", average(10,20)) Output: Area: 200

112 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


average: 15.0 Benefits of Python

1. Python is a dynamic-typed language. It means that you don't need to mention the data
type of variables during their declaration.

2. Python supports object-orientated programming as you can define classes along with the
composition and inheritance.

3. Functions in Python are like first-class objects. It suggests you can assign them to variables,
return from other methods and pass them as arguments.

4. Developing using Python is quick but running it is often slower than compiled languages.

5. Python has several usages like web-based applications, test automation, data modeling,
big data analytics, and much more.

g
UNIT-III

or
s.
Regular Expressions and Multithreaded Programming
te
Q. Special Symbols and Characters Regular Expressions:
da

regular expression is a special sequence of characters that helps you match or find other strings
p

or sets of strings, using a specialized syntax held in a pattern. Regular expression are popularly
known A
uu

as regex or regexp. Lisually, such patterns are used by string-searching algorithms for "find" or
an

"find and replace" operations on strings, or for input validation.


w

● Large scale text processing in data science projects requires manipulation of textual
w

data. The regular expressions processing is supported by many programming


languages including Python.
w

● Regular expressions in Python use special symbols and characters, called


metacharacters, to define search patterns.

● These metacharacters have specific meanings that extend the capabilities of simple
string matching.

Special Sequences

is to match a whitespace character

Aw to match an alphanumeric character.

113 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


W to match a non-alphanumeric character Ad to match a digit.

AD to match a non-digit character.

S to match a non-whitespace character

Quantifiers

? to match 0 or 1 repetition of the preceding pattern. (n.) to match n or more repetitions of


the preceding pattern.

(n) to match n repetitions of the preceding pattern.

(n.m) to match between n and m repetitions of the preceding pattern.

g
*to match 0 or more occurences of the preceding pattern.

or
s.
+ to match I or more occurences of the preceding pattern.
te
Metacharacters
da

Metacharacters are special characters with a defined meaning. They are used to perform
actions such as aggregation, pairing, reiteration, and pairing the search pattern.
p

Metacharacters are crucial for mastering Python regular expressions and are used in functions
uu

of the 're' module.


an
w
w
w

114 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex:
impon re

pattern a-zA-Z] string "123 abcXYZ matches re.findall(pattern, string)

print "Matches found", matches) Output: Manches found. WXYZ

Output : Match found Hello

Q. Res in Python

In the context of Python, "res" is commonly used as a variable name to represent the "result"

g
of a calculation or operation. It is not a reserved keyword or built-in function, but rather a

or
standard variable name chosen for its readability. The "re" module in Python is the built-in
module and fo working with regular expressions, also known as RegEx or Reges patterns.

s.
te
"res" as a variable name:
da

● Common Practice: Programmers often use "res" as a variable name to store the result
of a function call, a calculation, or any other operation.
p
uu

● Meaning:"res" is short for "result," and it clearly indicates that the variable will hold
the outcome of a process.
an

● Readability: This convention improves the readability of code by making it easy to


w

understand what a variable represents


w

"re" module for Regular Expressions:


w

● Built-in module: The "re" module in Python provides tools for working with regular
expressions.

● Purpose of Regular Expressions: Regular expressions are powerful patterns used to


search. match, and manipulate text based on predefined patterns.

● Common Operations: The "re" module allows you to search for patterns, extract
information

validate formats, and split strings based on patterns.

● Example:

115 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


WsCube Tech explains that the re.search() function can find the first match of a pattern in a
string

Other functions:

The "re" module includes functions like re.findall(), re.split(), and re.sub() for finding all
occurrences of a pattern, splitting a string based on a pattern, and replacing matches with
new strings, respectively.

In summary, "res" is a variable name used to store results, and "re" is the Python module for
working with regular expressions (RegEx or Regex patterns).

Q. Threads and Processes

Thread:

g
A thread is an entity within a process that can be scheduled for execution. Also, it is the

or
smallest unit of processing that can be performed in an OS (Operating System). In simple

s.
words, a thread is a sequence of such instructions within a program that can be executed
independently of other code For simplicity, you can assume that a thread is simply a subset
te
of a process!
da

A decad contains all this information in a Thread Control Block (TCB): Thread Identifier:
p

Unique id (TID) is assigned to every new thread


uu

Stack pointer: Points to thread's stack in the process. Stack contains the local variables under
thread's scope.
an

Program counter, a register which stores the address of the instruction currently being
w

executed by thread.
w

Thread states can be running, ready, waiting, start or done. Thread's register set: registers
w

assigned to thread for computations.

Parent process Pointer: A pointer to the Process control block (PCB) of the process that the

thread lives on.

Creating a Single Thread Ex

import threading def hello world(): print("Hello, world!")

116 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


threading. Thread(target-hello_world) L.start()

Output: hello world. Multithreading:

A programming method known as multithreading enables numerous threads of execution to


run simultaneously within a single process. A thread is a compact unit of execution that
symbolizes a separate control flow within a programme. A programme can use
multithreading to divide its tasks into smaller threads that can run concurrently, enabling
concurrent execution and possibly enhancing performance. Multithreading is helpful when a
programme must handle numerous separate activities or do multiple tasks simultaneously. It
permits parallelism at the thread level within a process, allowing work to be done
concurrently across tasks.

Data

g
Registersegsters Registers Stack

or
Stack Thread Thread

s.
Single-headed Process Multireaded Process Advantages of Threading
te
da
Threads improve the overall performance of a program. Threads increases the
p

responsiveness of the program Context Switching time in threads is faster.


uu

Threads share the same memory and resources within a process. Communication is faster in
an

threads.
w

Processes:
w
w

117 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Processes are basically the programs that are dispatched from the ready state and are
scheduled in the CPU for execution. PCB (Process Control Block) holds the context of
process. A process can create other processes which are known as Child Processes. The
process takes more time to terminate, and it is isolated means it does not share the memory
with any other process. The prouns can have the following statsz new, ready, running,
waiting, terminated and suspended.

PROCESS

Difference Between Process and Thread Process Process means a program in execution.

A process takes more time to terminate. It takes more time for creation.

It also takes more time for context switching.

g
A process is less efficient in terms of communication. Every process runs in its own memory.

or
A process does not share data with each other A

Thread
s.
te
da
Thread means a segment of a process A thread takes less time to terminate
p

It takes less time for creation


uu

It takes less time for context switching


an

Thread is more efficient in terms of communication. Threads share memory


w

Threads share data with each other


w

Q. Python Threads
w

Thread: A thread is a lightweight unit of execution within a process. Multiple threads can
exist within the same process, sharing the process's memory space and resources.

118 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Multithreading: Multithreading is a technique that allows a program to execute multiple
threads concurrently. This can improve performance by enabling parallel execution of tasks,
especially when dealing with I/O-bound operations.

Creating a Single Thread:

Ex:

import threading def hello_world():

print("Hello, world!")

1-threading.Thread(target-hello_world) t.start()

Output hello world Life Cycle of a Thread

g
There are multiple states of the thread in a lifecycle as mentioned below:

or
s.
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code is
te
yet to be run and has not started to execute.
da

2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
p

thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the threadscheduler to give the thread, time to run. A multi-threaded
uu

program allocates a fixed amount of time to each individual thread. Each and every thread
get a small amount of time to run. After running for while, a thread pauses and gives us the
an

CPU so that other threads can run


w

3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but
w

currently the lock is acquired by the other thread. The thread will move from the blocked
state to runnable state when acquires the lock
w

4. Waiting state. The thread will be in waiting state when it calls wait) method or join()
method, it will move to the runnable state when other thread will notify or that thread will
be terminated.

5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-
oỢা parameter. A thread lies in this state until the timeout is completed or until a
notification is received, For a timed waiting

6. Terminated State: A thread terminates because of either of the following reasons:

119 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Because it exits normally. This happens when the code of the thread has been entirely
executed by the

program Because there occurred some unusual erroneous event, like a segmentation fault or
an unhandled exception.

Q. Global Interpreter Lock

The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects,
preventing multiple threads from executing Python bytecodes simultaneously. This means
that, despite Python being a multi-threaded programming language, only one thread can
execute Python code at a time. The GIL. ensures that memory management is thread-safe,
which simplifies the implementation of Python and protects it from certain types of

g
concurrency issues.

or
CPU

Python Code
s.
te
da
thread thread2y thread

→ CPU
p
uu

Interpreter Lock CPU


an

GIL Work:
w

The GIL works by acquiring and releasing a lock around the Python-interpreter A thread
w

must acquire the GIL whenever it wants to execute Python bytecode. If another thread has
already acquiredthe GIL, the requesting thread has to wait until it is released. Once the
w

thread finishes executing the bytecode, it releases the GIL, allowing other threads to acquire
it.

Python Have a GIL:

The GIL was introduced in the early days of Python as a means to simplify memory
management and make the interpreter easier to implement. Here are a few reasons why it
was deemed necessary

a) Memory Management: Python uses reference counting for memory management.


Without the GII., reference counting would require more complex locking mechanisms,
which could lead to performance overhead and deadlocks.

120 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


b) Ease of Implementation: The GIL simplifies the implementation of Python (the standard
Python interpreter), making it easier to develop and maintain. It reduces the need for
intricate locking and threading designs.

c) Compatibility: A single-threaded model makes it easier for extensions and third-party


libraries to work seamlessly with Python's memory model.

Implications of the GIL

1. CPU-bound Tasks: In CPU-bound programs (tasks that require heavy computation), the
GIL. can be a bottleneck. Since only one thread can execute Python code at a time,
multi-threading may not lead to performance gains. For CPU-bound tasks, utilizing
multi-processing (using the multiprocessing module) is often a better approach, as it spawns
separate processes that can run

g
on different CPU cores. 2. I/O-bound Tasks: The GIL is less of an issue for I/O-bound tasks

or
(tasks that spend a lot of time waiting for input/output operations). Threads can release the

s.
GIL, when waiting for 1/0 operations, allowing other threads to run. This makes threading a
viable option for applications that are I/O-
te
da
heavy, such as web servers. 3. Concurrent Programming: With the introduction of
asynchronous programming (using asyncio), many developers have shifted towards using
async and await constructs, which allow for writing concurrent code that doesn't rely on
p

threads. This can help avoid GIL-related issues while still achieving concurrency.
uu

Advantages of the GIL


an

Simplifies memory management and makes it easier to write thread-safe code. Provides a
w
w

level of safety by preventing race conditions and deadlocks.


w

Allows for efficient execution of I/O-bound tasks through thread-based concurrency.

Disadvantages of the GIL

Limits the benefits of multithreading for CPU-bound tasks.

It can introduce overhead and degrade performance in certain scenarios.

Requires alternative approaches, such as multiprocessing or asynchronous programming, for


optimal performance.

Thread Handling Modules in Python

Thread Handling Modules in Python Python's standard library provides two main modules
for managing threads: thread and threading.
121 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Q. Thread Module The Thread Module:

The thread module, also known as the low-level thread module, has been a part of Python's
standard library since version 2. It offers a basic API for thread management, supporting
concurrent execution of threads within a shared global data space. The module includes
simple locks (mutexes) for synchronization purposes.Starting a New Thread Using the_thread
Module:

The start new thread() method of the thread module provides a basic way to create and
start new threads. This method provides a fast and efficient way to create new threads in
both Linux and Windows

This method call returns immediately, and the new thread starts executing the specified
function with the given arguments. When the function returns, the thread terminates.

g
syntax thread start new thread(function, args[, kwargs])

or
Ex: This example demonstrates how to use the thread module to create and run threads.

s.
Each thread runs the print name function with different arguments. The time sleep(0.5) call
ensures that the main program waits for the threads to complete their execution before
te
exiting.
da

import thread import time


p

def print_name(name, *arg) print(name, arg)


uu

name "Tutorialspoint."
an

thread start_new_thread(print name, (name, 1)) thread start new thread(print_name, (name,
w
w

1, 2)) time.sleep(0.5)
w

Output: Tutorialspoint... I Tutorialspoint 12

The Threading Module

122 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Q. Threading Module

The threading module, introduced in Python 2.4, builds upon thread to provide a higher-
level and more comprehensive threading API. It offers powerful tools for managing threads,
making it easier to

work with threads in Python applications. Features of the threading Module threading

activeCount() Returns the number of thread objects that are active.

threading current Thread() Returns the number of thread objects in the caller's thread
control.

threading enumerate() Returns a list of all thread objects that are currently active.

g
In addition to the methods, the threading module has the Thread class that implements
threading. The

or
s.
methods provided by the Thread class are as follows -run() The run() method is the entry
point for a thread.
te
da
start() The start() method starts a thread by calling the run method. join([time]) The join()
p

waits for threads to terminate.


uu

isAlive() The isAlive() method checks whether a thread is still executing. getName() The
an

getName() method returns the name of a thread. setName() The setName() method sets the
w

name of a thread.
w

Starting a New Thread Using the Threading Module


w

The threading module provides the Thread class, which is used to create and manage
threads.

Here are a few steps to start a new thread using the threading module Create a function that

you want the thread to execute.

Then create a Thread object using the Thread class by passing the target function and its
arguments.

Call the start method on the Thread object to begin execution.

Optionally, call the join method to wait for the thread to complete before proceeding.
Ex: The following example demonstrates how to create and start threads using the threading
123 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
module. It runs a function print_name that prints a name along with some arguments. This

g
or
s.
te
p da
uu
an
w
w
w

124 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


example creates two threads, starts them using the start() method, and waits for them to
complete using the join method.

def print_name(name, *args):

print(name, args) name "Tutorialspoint..."

#Create and start threads

thread1 = threading. Thread(target-print_name, args (name, 1)) thread2

threading.Thread(target=print_name, args (name, 1, 2)) thread1.start()

thread2.start()

g
#Wait for threads to complete thread1.join()

or
thread2.join()

print("Threads are finished...exiting") Output:


s.
te
da
Tutorialspoint... 1

Tutorialspoint... 12
p
uu

Threads are finished...exiting


UNIT-IV
an

GUI Programming
w
w

Q. Tkinter and Python Programming


w

Python Tkinter is a standard GUI (Graphical User Interface) library for Python which
provides a fast and easy way to create desktop applications. Tkinter provides a variety of
widgets like buttons, labels, text boxes, menus and more that can be used to create
interactive user interfaces Tkinter supports event-driven programming, where actions are
taken in response to user events like clicks or keypresses, It's cross-platform, meaning
applications built with Tkinter can run on Windows macOS, and Linus without modification.

To install Tkinter

125 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Tkinter comes as part of standard Python installation. So if you have installed the latest
version of Python, then you do not have to do anything else. You can determine whether
Tkinter is available for your Python interpreter by attempting to import the Tkinter module.

Syntax: import tkinter

Create First Tkinter GUI Application

1. Import the tkinter module.

2. Create the main application window.

3. Add the widgets like labels, buttons, frames, etc. to the window.

4. Call the main event loop so that the actions can take place on the user's computer screen.

g
Tkinter Methods

or
s.
Tk() To create a main window in Tkinter, we use the Tk() class. The syntax for creating a
main
te
da
window is as follows:

Syntax root tk. Tk(screenName=None, baseName=None, className=Tk', useTk=1)


p
uu

screenName: This parameter is used to specify the display name. This parameter can be used
to set the base name of the application.
an

baseName:
w
w

className: We can change the name of the window by setting this parameter to the desired
w

name.

useTk: This parameter indicates whether to use Tk or not.

mainloop():

This method is used to start the application. The mainloop() function is an infinite loop that

is used to run the application. It will wait for events to occur and process the events as long
as the window is not closed.

tkinter Example:

import tkinter

126 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


top-tkinter.Tk() #creating the application main window.

g
or
s.
te
p da
uu
an
w
w
w

127 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


top.title("Welcome") #title of main window top.geometry("400x300") #size of main

window top.mainloop() #calling the event main loop Title of window

Main Window (400x300) Common Tkinter Widgets

Here are some of the commonly used Tkinter widgets

2. Label: This is used to display simple text.

Button: A simple button that can be clicked to perform an action.

3. Entry: Simple input field to take input from the user. This is used for single-line input. 4

. Text: This can be used for multi-line text fields, to show text, or to take input from the user

g
. Canvas: This widget can be used for drawing shapes, images, and custom graphics.

or
s.
5 6. Frame: This acts as a container widget that can be used to group other widgets together
te
7 Checkbutton: A checkbox widget used for creating toggle options on or off
da

. Listbox: This is used to create a List widget used for displaying a list of values. 10. Scrollbar:
This widget is used for scrolling content in other widgets like Text and Listbox.
p
uu

8. Radiobutton: This is used to create Radio buttons. 9 Fonts, Colors, Images in Tkinter
an

of For Ex:
w

The choice of fonts, colors, and images can make a significant impact on the user experience
w

and the overall aesthetic appeal of an application.


w

Fonts Colors

Choose color Dialog

128 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Images

Loading Images in Tkinter using PIL Resize Image

Images as Backgrounds a ater ks

import tkinter as tk #Create the main window window tk.Tk()

window.title("My First GUI") #Create a label widget

labeltk.Label(window, text="Hello, Tkinter!") label.pack()

#Create a button widget

button tk.Button(window, text="Click Me") button.pack()

g
#Run the main loop (to display the window and handle events) window.mainloop()

or
s.
Q. Brief Tour of Other GUIs te
Python has plenty of frameworks for developing GUIs that deliver a high-quality user
da
experience without a hefty price tag. Here are some of the most popular Python GUI
frameworks used by developers.
p

1. PyQt5
uu

Riverbank Computing's PyQt package is built around the Qt framework, which is a


an

cross-platform framework used for creating a plethora of applications for various platforms.
w

The PyQt5 package includes a detailed set of bindings for Python based on the V5 version of
w

the Qt application framework.


w

129 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Similar to the Qt5 framework, PyQt5 is also fully cross-platform and supports applications

for platforms like Windows, Mac, Linux, iOS, Android and more.

Key features:

Compatible with Windows, Mac, Linux, iOS and Android platforms


Oriol and QtDesigner modules support drag-and-drop features Online documentation and
resources available due to PyQt5's popularity
2. Tkinter

Oriol and QtDesigner modules support drag-and-drop features Online documentation and
resources available due to PyQt5's popularity

Often referred to as the go-to GUI toolkit by a majority of Python developers, Python

g
contributor Fredrik Lundh created Tkinter to equip modern developers with a standard
Interface to the Tk GUI toolkit with its Python bindings.

or
s.
In Tkinter's world, most of the visual elements that we're familiar with are called widgets
and each of these widgets offers a different level of customizability.
te
da
3. Kivy
p

Written using a mix of Python and Cython. Kivy is an open-source GUI framework Va
building user interfaces encompassing multi-touch applications.
uu

It implements a natural user interface (NUI) a kind of interface where the user naturally
an

usually kept invisible learns about the various interactions provided by a user interface that's
w

The most common use of the Kivy GUI framework can be seen in Android and applications.
w

Other widespread implementations of the framework can be seen in the user interfaces of
Linux, Windows, Raspberry Pi and macOS devices.
w

Key features:

Free and open-source, despite being under the MIT license.

Provides built-in support for OpenGL ES 2 to create powerful graphics. Compatible with

Linux, Windows, Raspberry Pi and macOS devices.

4.

wxPyleveloped by programmer Robin Dunn, wxPython is a Python extension module that


acts as a wrapper for the wxWidgets API.

wxPython allows Python developers to create native user interfaces that add zero additional
130 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
overhead to the application. The cross-platform capabilities of wxPython allow deployment
to

g
or
s.
te
p da
uu
an
w
w
w

131 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


platforms like Windows, macOS, Linux, and Unix-based systems with little to no
modifications.

Key features:

Supports the development of native user interfaces. Designed to make the wxWidgets toolkit

easier to use. Compatible with Windows, macOS and Linux platforms.

5. Libavg

This open-source Libavg GUI framework is great for developing user interfaces for modem
touch-based devices.

On the graphics-intensive side, video decoding, visual effects and compositing are all

g
handled by the hardware acceleration achieved via OpenGL and GPU shaders to deliver
smooth and graphic-rich visuals.

or
s.
ibavg supports a majority of commonly used touch drivers and offers a range of features, such
as camera support, text alignment, animation support and GPU effects like blur and shadows.
te
da
Key features:
p

Ideal for building touch-based devices.


uu

Uses OpenGL to support video decoding, compositing and other capabilities. Possesses
an

features like text alignment, animation support and GPU effects,


w

6. PySimpleGUI
w

PySimpleGUI is designed for Python newbies to get into GUI development without spending
w

too much time getting into the intricacies of the more advanced GUI development options
available.

PySimpleGUI takes four of the widely popular Python GUI frameworks Qt, Tkinter.
wxPython and Remi and turns down their difficulty a few notches by implementing most of
the boilerplate code.
Beginners get to pick the GUI framework of their choice, along with easy access to the
various visual elements that come with it to create intuitive user interfaces without diving
deep into the frameworks.

7. Py Forms

132 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Pyforms is a Python software layer at its core for the widely famous Windows Forms, which
allows developers to create highly interactive user interfaces.

PyForms' cross-platform capabilities make it easier to create applications for multiple


platforms with little changes to the code, eliminating unnecessary slowdowns

PyForms provides several popular graphic-centric libraries, such as PyQt and OpenGL, to
help developers create user interfaces for their applications.

The PyForms library is split into three different sections that include PyForms-GUI, PyForms-
Web and PyForms-Terminal.

Key features:

Offers popular libraries like PyQt and OpenGL. for building user interfaces. Can be executed

g
in web, terminal and Windows GUI

or
s.
Ideal for quickly building prototypes and supporting application maintenance.
te
8. Wax
da

Just like wxPython was a wrapper for the wxWidgets GUI toolkit, the Wax GUI framework
p

is a more developer-friendly wrapper of wxPython.


uu

Like other popular frameworks, Wax is implemented as an extension module for Python.
And it also supports building cross-platform applications.
an

The idea behind Wax is to offer developers simpler access to the Python elements and
w

objects for building GUIs by removing the low-level aspects of wxPython.


w

Key features:
w

Serves as a user-friendly wrapper of wxPython.

Uses native widgets, matching the speed and efficiency of wxWindows. Open-source for

anyone to use.

Q. Web Surfing with Python

This program will take in a search string from you and automatically search for it, Collect the
web pages, and serve them to you one by one in a tabbed browser. So sit back, relax, and
let the program

do the work for you

133 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Web Surfer Program Works

g
or
s.
te
p da
uu
an
w
w
w

134 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The web surfer program is built using Python and leverages various modules and libraries to
achieve its functionality. Here's a brief overview of how it works:

Collect the search string from the user.

Use the Requests module to send a search query to a search engine (e.g., Google). Retrieve

the results page using the Requests module.

Parse the HTML of the results page using the Beautiful Soup library. Extract the links from

the parsed HTML..

Open each link in a new tab using the Web Browser module.

g
Set a random sleep interval between page loads to simulate natural browsing behavior.

or
s.
The Benefits of Using the Web Surfer Program te
a) Time-saving: Instead of manually searching for web pages and clicking on each result, the
da
program automates the process, saving you time and effort.

) Convenience: The program serves the web pages to you in a tabbed browser, allowing you
p

to b sit back and watch them like you're watching TV


uu

c) Passive browsing: By automatically loading each web page in a new tab, the program
an

creates a passive browsing experience where you can effortlessly browse through different
results.
w
w

d) Research efficiency: The program is particularly useful for researchers who need to quickly
scan through multiple web pages throughout the day
w

Step-by-Step Guide on Creating the Web Surfer Program

Now, let's dive into the step-by-step process of creating the web surfer program.

1. Collecting the Search String

The first step in creating the web surfer program is collecting the search string from the user

This can be done using the sys

module in Python. Here's an example of how to capture the search string: import sys

#Get the search string from the command line arguments

135 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


search string join(sys.argv[1:])

2. Getting the Results Page

Once we have the search string, we need to send it to the search engine and retrieve the
results page, We can achieve this using the Requests Ex:

import requests #Assemble the URL

search_query=https://www.google.com/search?q=search_string #Get the results page

response requests.get(search_query) #Check if the page was fetched successfully if

response.status code requests.codes.ok results page response.text else:

g
print('Error in fetching the web page") sys.exit(1)

or
3. Parsing the Results Page with Beautiful Soup

s.
Next, we need to parse the HTML of the results page to extract the links. This can be
te
achieved using the
da

Beautiful Soup Ex:


p

from bs4 import BeautifulSoup


uu

#Create a Beautiful Soup object with the results page HTML soup page
an

BeautifulSoup(results_page, 'html.parser') #Extract the links from the soup page


w
w

links soup page.find_all('a') #Print out the links


w

136 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


for link in links:

print(link.get('href'))

4. Extracting the Links from the Results Page

Once we have the links, we can extract them and store them in a list. Here's an example of
how to

do it:

Ex

def get_links(soup_page):

g
#Extract the links from the soup page links soup_page.find_all('a')

or
#Create a list of the href attributes extracted_links [link.get('href') for link in links] return

extracted links
s.
te
da
5. Opening the Links in New Browser Tabs

Finally, we can open cach link in a new tab using the webbrowser Ex
p
uu

import webbrowser
an

#Open each link in a new browser tab


w

for link in extracted links: webbrowser.open_new_tab(link) Web client definition:


w

Q Creating Simple Web Clients


w

A web client is a software application that uses hypertext transfer protocol (HTTP) to
format, transmit, and receive requests, web content, services, or resources from web servers.
It's often called a web browser but a web client is a wider term that encompasses both web
browsers and web applications.

Advanced web clients:

137 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Advanced web clients are more than just simple web browsers; they are applications that
perform complex tasks, often involving automated interactions with the web. They can be
used for tasks like web scraping, testing websites, or accessing services through web
interfaces, often requiring more sophisticated functionality than a basic web browser.

Examples of Advanced Web Clients:

Web Scrapers (Crawlers): These clients automatically download and analyze web pages,
often used for gathering information, testing websites, or automating tasks O'Reilly Media
says Testing Tools: Applications that automate website testing, including performance
testing. compatibility testing, and security testing.

Web Service Clients: These clients interact with web services to perform actions or retrieve
data, often used in applications that require access to external APIs ScienceDirect.com says-

g
Advanced Browser Features: Some web browsers offer advanced features beyond basic
browsing. such as developer tools, built-in scraping capabilities, or extensions that enhance

or
functionality NordVPN says.

s.
Specialized Web Applications: Web-based applications that offer advanced features, such as
te
virtual desktop environments, remote access software, or collaborative tools
da
enterpriseopen.com says.
p

Key Features of Advanced Web Clients:


uu

Automation: Many advanced clients automate tasks, such as data extraction or website
testing.
an

Programmability: Some clients allow for custom scripting or programming to enhance their
w

functionality.
w

Extensive Capabilities: They offer a wider range of features than basic web browsers,
w

including advanced filtering, data manipulation, and reporting.

Integration with Other Systems: They can integrate with other systems or services, enabling
seamless workflow.

Performance and Scalability: Advanced clients often prioritize performance and scalability.
allowing for efficient handling of large amounts of data or complex tasks
enterpriseopen.com says.

Q. Advanced Web Clients

Advanced web clients are web-based applications or software that go beyond basic web
browsing functionality. They often involve complex interactions with web servers, use
modern frameworks, and can be designed to handle various tasks like indexing websites,
offline browsing, or accessing services through web service clients.
138 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Advanced weh technology refers to the use of modern tools, frameworks, and techniques to
cro dynamic efficient, and interactive web applications. This includes technologies like
11TML5, CSS3 JavaScript frameworks, and APIs

1. Beyond Basic Browsing:

Standard web browsers are basic clients that primarily handle viewing and downloading
web pages Advanced clients perform more complex operations, such as crawling and
indexing the web.

Examples include programs that download entire websites for offline viewing, bots used for
scraping data, or web service clients that interact with web services.

2. Modern Frameworks and Technologies:

g
Advanced web development often utilizes frameworks like React. Angular, and Vue.js to
create complex and interactive applications.

or
s.
These frameworks provide tools for building reusable components, managing application
state, and handling client-side logic.
te
da
Advanced techniques like AJAX (Asynchronous JavaScript and XML) and the Document Oby
Model (DOM) are used to dynamically update web pages without requiring full page reloads.
p

3. Examples of Advanced Clients: a


uu

) Crawlers (Web Robots): These programs systematically explore and download web pages
an

for indexing search engines, archiving, or data extraction.


w

b) Oftine Browsing Tools: Programs that download web pages and create a local mirror of
w

the site for c)


w

offline access. Web Service Clients: Applications that interact with web services (API
endpoints) to retrieve data, perform actions, or access remote resources.

Virtual Desktop Infrastructures (VDIs):EO.workspace offers a VDI that allows users to access
their desktop environment and applications through a web browser, supporting features like
file transfer, printing, and smartcard usage.

) Webmail Clients:Zimbra's Web Client offers features like email composition, contact e
management, calendaring, and task management.

Enterprise Applications:vSphere Web Client (like Broadcom's vSphere) provides web-based


interfaces for managing virtual machines and infrastructure.

Essential Skills for Advanced Web Developers

139 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


React: Developed by Facebook, React is a library for building user interfaces, especially
single-page applications where you don't need to reload the page as the user interacts with
it. React allows developers to create reusable Ul components, making the code more
modular and easier to maintain.

Angular: Created by Google, Angular is a comprehensive framework for building web


applications. It's well-suited for developing single-page applications, offering built-in features
for routing, state management, and form handling.

CGI:

Q. CGI-Helping Servers Process Client Data

CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set
of rules (specification) that establishes a dynamic interaction between a web application and

g
the client application (or the browser). The programs based on CGI helps in communicating
between the web servers and the client. Whenever the client browser makes a request, it

or
sends it to the webserver, and the CGI programs return output to the webserver based on

s.
the input that the client-server provides.
Common Gateway Imerface (CGI) provides a standard for peripheral gateway programs to
te
interface with the data servers like an HTTP server
da

The programming with CGf is written dynamically, which generates web-pages responding
p

to the input from the user of the web-pages interacting with the software on the server
uu

CGI Architecture Diagram


an

Common Gateway Interface Works:


w

The following common gateway diagram helps to understand how CGt works when a user
w

clicks a hyperlink to search and browse any web page. A web browser operating on a client
machine uses Hyper Text Transfer Protocol (HTTP) to exchange information with a web
w

server

The CGI program resides on the same system where the webserver is present and they
operate from the same system. Based on the request type received from the browser, the
web server attempts to either provide the document from its document file system or run a
CGI program. Following are a series of events to create an HTML document using CGI
scripts:

A user requests the HTTP web server and demands the URL. The user can also type the URL
in a browser's location window, which can be a hyperlink or specified as HTML <form> tag

The web server will analyze the URL and looks for the filename. Otherwise, it activates the
gateway program mentioned in the URL. and sends parameters to the program via the URL

140 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The Common Gateway Interface gateway processes the required information and sends
file/HTML text to the webserver. Additionally, the server appends the MIME header and
sends the HTML text to the browser.

Taking the result from a web server, the web browser displays either the received document
or an error message.

Applications of Common Gateway Interface:

CGI transforms the Web from collecting static data into a new interactive structure, wherein
users can interact with the number of questions to run applications. Some of the applications
that are designed using CGI are

2) Forms: Forms are one of the most significant users of CGI. Forms allow the user to share
information and is a subset of HTML A CGI program makes these forms very interactive for

g
both user and provider by processing and selecting the appropriate forms that match the
selection criteria.

or
s.
b) Gateway Web gateways are alike programs or scripts. It is used to access the necessary
information that is not directly readable by the client from the database. The CGI program is
te
employed to serve as a gateway and use appropriate programing language to read the
da
information, format, and share it with the client.
p

c) Virtual Documents Virtual document creation is the most important part of CGL While
virtual documents are created as per the user's request, they can vary from virtual HTML,
uu

images, plain text to sometimes audio.


Features of CGI
an

CGf is utilized to create simple shell scripts and interactive application They are well defined
w
w

with a set of rules


w

CG is a technology that catily interfaces with HTML Perl, C

CGf is highly compatible with existing browsers. Advantages of Python CGI Programming

1. They are portable, can work on many operating systems and web servers.

2. These are independent of the language of the script. 3. The programs are scalable in
nature, they can perform both simple and complex tasks.

4. These develop dynamic communication in web applications

5. These decrease the development and maintenance costs.

141 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Q. Building CGI Application

Steps Involved in Creating a CGI Script

Here are the steps involved in creating a basic Common Gateway Interface script:

1. Choose a Programming Language:

Decide which programming language you will use for your CGI script. Standard options
include Port

Python, or PHP

2. Set Up Your Environment:

g
Make sure your web server (Apache, Nginx, etc.) has been configured properly for handling

or
CGL scripts; usually, this involves enabling Cils within the server configuration file and setting

s.
up the te
appropriate directory.
da

3. Write the Script:


p

Use some lext editor to create a new file for your script. Typically, the extension reflects the
uu

language used (pl for perl, py for python)


an

Write script code that handles requests and generates responses. Ensure it starts with the
correct shebang line, depending on what language was chosen.
w
w

4. Set Permissions:
w

Change permissions of file in such a way that allows execution of script: normally done
through command line using chmod.

5. Place the Script on the server:

Move the script to the server's CGI directory. This directory is typically set up to handle
executable files.

6. Test the Script:

Open a web browser and navigate to the script's URL. Thereafter, check the output to
ensure the script executes correctly and generates the expected response.

7. Debug and Refine:

142 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


If the script doesn't work as expected review server logs or error messages to troubleshoot
issues. Therefore, edit the script based on feedback or errors and retest to ensure it performs
as intended.

8. Security and Maintenance:

Ensure the script is secure, mainly if it handles sensitive data. Therefore, implement proper
validation and sanitation of inputs.

Regularly update and maintain the script to address any new issues or requirements. HTTP

headers used in CGI Programming

There are a few additional essential HTTP headers that you will regularly utilize when
developing CGI programs.

g
or
In CGI programming, HTTP headers provide additional information about the response to

s.
the client web browser. Some of the essential HTTP headers that are commonly used in CGI
programming include:
te
da
1. Content-Type: This header specifies the media type of the response body, such as
text/html for HTML content or application/json for JSON data.
p

2. Content-Length: This header specifies the size of the response body in bytes. This is
uu

important for the client browser to know how much data to expect and when the response
is complete
an

3. Location: This header redirects the client to a different URL. It is commonly used in
w

conjunction with the 3xx HTTP status codes, such as 301 (Moved Permanently) or 302
w

(Found).
w

4. Set-Cookie: This header sets cookies on the client browser Cookies, which are stored on the
Client's Computer, are Small pieces of Data. They are sent back to the server with each
subsequent request. They store user preferences, session information, or other data.

5. Cache-Control: This header controls how the client or intermediate proxies cache the
response. It can be used to specify that the response should not be cached or that it should
only be cached for a certain amount of time.

CGI Get and Post Methods

We must have encountered many situations where we need to pass some information from
our browser to a web server and finally to our CGI program. The browser most often uses
two methods to pass this information to the web server These methods are the GET method
and the POST method.

143 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Passing Info using GET Method

g
or
s.
te
p da
uu
an
w
w
w

144 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The GET method sends encoded user information attached to the page request. The page
and encoded information are separated by a 7 sign like-

http://www.testing.com/cgi-bin/hellouser.py?keyl value1&key2 value2

The GET method is the default method for passing information from a browser to a web
server and produces a long string that appears in your browser's Location:box. Never use the
GET method if you have a password or other sensitive information to pass to the server. The
GET method has a size limit: only 1024 characters can be sent in the request string.
The GET method sends information using the QUERY STRING header and will be accessible
in your CGI program via the QUERY STRING environment variable.

You can pass information by simply concatenating key-value pairs along with any URL, or
you can use HTML <FORM> tags to pass information using the GET method.

g
CGI Environment Variables using Python

or
s.
In CGI programming, environment variables store information about the request and the
server environment. The CGI program can access these variables and generate a dynamic
te
response. You can access the CGI environment variables in Python using the os module.
da
This module provides

an environment dictionary that contains the current environment variables. For example,
p

you can access the REQUEST_METHOD variable, which specifies the HTTP method of the
uu

request, using the following code:


an

import os methodos.environ["REQUEST_METHOD"] CGI environment variables


w

There are many other CGI environment variables that you can access in this way. Some of
w

the common ones include:


w

QUERY STRING: The query string of the URL, if any.


CONTENT_TYPE: if provided, they are the media type of the request body.

CONTENT_LENGTH: The size of the request body in bytes, if provided.

HTTP COOKIE: The cookies sent by the client with the request. REMOTE ADDR: The IP
address of the client computer that makes the request.

Q. Advanced CGI

Advanced CGI programming in Python involves techniques that go beyond basic form
handling and output generation. These techniques include using cookies, handling multiple
values for the same form field, and managing file uploads.

145 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


➤ Cookies:

Cookies enable personalized browsing. With cookies we can store information about a client
For example, about previous selections made, in passing data from one script to another We
can store personal information such as identification and passwords; or information from
previous visits to the site. Potential applications include customizing displayed content,
storing encrypted password for fast

access, personalized pricing Cookies are data

stored by web server on elient computer, managed by the browser.

The session below illustrates the use of the cookies module.

from http import cookies ccookies.SimpleCookie() c[L]-35 c['data'] = 'Fri 8 Apr 2016'

g
print(c) Set-Cookie: L-35

or
Set-Cookie: data="Fri 8 Apr 2016" Password Encryption

s.
We can use cookies for login names and passwords. For security purposes, we store only the
te
encrypted passwords.
da

A secure hash algorithm is often called a trapdoor function, as it is computationally infeasible


p

to compute its inverse. As a hash function, the collision rate is low, which means that there is
a very low chance that two different messages will generate the same key.
uu

The server encrypts the password before sending it to the client. The authentication happens
an

by comparing encrypted passwords.


w

A session with the hashlib module is illustrated below. from hashlib import shal m'this is me'
w

hshal (m.encode())
w

<shal HASH object @ 0x1019a53f0> h.hexdigest()


99cf08cddcc3ae19fae7ec8f5315179786611406'

Authentication via Email

We can restrict access to our web application via a third party email authentication. For
example, we may grant access only to those with a valid UIC email account.

146 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


The Simple Mail Transfer Protocol (SMTP) is an internet standard for email transmission. In
Python we can send email using smtplib. For example, to connect to the [tt gmail) email
server, consider the

session below: from smtplib import SMTP SMTP(smtp.gmail.com, 587)

s.startils()

(220, b'2.0.0 Ready to start TLS')

➤ File Uploads:

File uploads are handled using the multipart/form-data encoding. The cgi. Field Storage
object treats uploaded files as file-like objects, which can be read and processed. To upload a
file, the HTML form must have the enctype attribute set to multipart/form-data. The input

g
tag with the file type will create a "Browse" button.

or
Ex

<html>
s.
te
da
<body>

<form enctype="multipart/form-data" action="save_file.py" method="post">


p
uu

<p>File: <input type="file" name="filename" /></p>


an

<p><input type="submit" value="Upload" /></p>


w

</form>
w

</body>
w

</html>

File Download" Dialog Box:

Sometimes, itis desired that youwantto give optionwhere a user will click a link and it will
pop up a "File Download" dialogue box to the user instead of displaying actual content. This
is very easy and will be achieved through HTTP header. This HTTP header will be
differentfromthe header mentioned inprevious section. For example, if youwant make a
FileName file downloadable from a given link, then its syntax will be as follows:

Ex

147 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


#!/usr/bin/python #HTTP Header

print "Content-Type:application/octet-stream; name=\"FileName\"\r\n"; print "Content-

Disposition: attachment; filename=\"FileName\"\r\n\n"; #Actual File Content will go hear.

foopen("foo.txt", "rb") strfo.read();

print str

#Close opend file fo.close()

Q. Web (HTTP) Servers

g
A web server is actually a network application, running on some machine, listening on some
port.

or
s.
Web server is a computer where web contents are stored.
te
A web server serves web pages to clients across the internet or an intranet
da

It hosts the pages, scripts, programs and multimedia files and serve them using HTTP, a
protocol
p
uu

designed to send files to web browsers.


Apache web server, IIS web server. Nginx web server, Light Speed web server etc are the
an

common examples of web servers.


w

Types
w

There are two types of web servers-


w

Dedicated web servers: In this, one web server is dedicated to a single user. This is suitable

for websites more web traffics. Shared web with her in this, a web server is assigned to many
clients and it shared among all the clients.

Web Server Works

148 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


HTTP OET

Accept-Encoding gzp de fate Web Browser

Danides

200 OK Content-Encoding detate Web Server

HTML, CSS, etc

compressed fles cache

working For eg, a user wants to see a website like (www.google.com), the user type in the
url the page using a client program(web browsers) but before this they need to physically
connected te the computer of the user and the web server, that's the job of Internet. Using

g
the TCP/IP suite of protocol, it establishes the connection using a combination of cable
media and wireless

or
s.
media. When the connection is establishes, the client sends a request called an http message
and because the HTTP is a connectionless protocol, the clients disconnects from the server
te
waiting
da

for the response. The server on the other side process the requests, prepare the response,
p

establishes the connection again and send back to response.


uu

Again inform a HTTP message to the client when the two computer is completely
disconnect, that is the big general.
an

HTTP Protocol
w
w

It stands for Hyper Text Transfer Protocol.


w

It is an application layer protocol that allows web based applications to communicate and

exchange data.

The HTTP is the messenger of web.

The computer that communicate via the HTTP must speak the HTTP protocol. It is a TCP/IP

based protocol.

It is used to deliver contents, for eg, images, audios, videos, documents etc.

149 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Using HTTP is the most convenient way to quickly and reliably move data on the web.

Features of the http.server module includes:


Base HTTP Functionality The hite server

ile opports Mandand UVTP methods audi as GET and HEAD allowing developers to handle
simple reg Easy Setup Creating an HTTP servering the http server mushile complires minimal
code You can easily setup a functional server with

just a few fue of le 1. Statie File Serving The module can serve static Bles, making it helpful in
hosting simple websites or web applications that reb on static content Customizable Request
Handling: Static files are default

2 served from the current directory Himever, developers have the option to create
customized request handlers that can handle sivitie Dies of requests du serve dynamic

g
content Portability Python is a cross-platform language, and the HTTP server coule is widten
using the hity server module will work consistently across differem operating systemis

or
s.
e all te
UNIT-V
da

Database Programming
p

Q. Python Database Application Programmer's Interface (DBAPI) Database:


uu

A database is basically a collection of structured data in such a way that it can easily be
an

retrieved, managed and accessed in various ways. Relational databases are the most popular
database system which includes the following:
w
w

MySQL
w

Oracle Database SQL server

IBM db2 NO SQL

MySQLdb:

MySQLdb is an open-source freely available relational database management system that


uses Structured Query Language. SQL (Structured Query Language) is a standard language for
relational databases that allow users to do various operations on data like, Manipulating,
Creating. Dropping.

150 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Python connect to a database
It is very simple to connect Python with the database Refer the below image which illustrates
Python connection with the database where how a connection request is sent to MySOL
connector Python, gets accepted from the database and cursor is executed with result data.

Python DB API

Python DB API v2.0 (PEP 249)

Python Application mysal.connector connect() connection.cursor() Cursor execute()

MySQL Connector Python Connection request connected B

g
result data 6 MYSQL

or
s.
Before connecting to the MySQL database, make sure you have MySQL installer installed on
your computer. It provides a comprehensive set of tools which helps in installing MySQL
te
with the following components:
da

MySQL server
p

All available connectors MySQL Workbench MySQL Notifier


uu

MySQL Sample Databases


an

parameters required to connect to the database:


w
w

Username- It is simply the username you give to work MySQL server with, the Default
w

151 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


username is root. Password- Password is given by the user when you have installed the
MySQL database

Host Name- This basically is the server name or IP address on which your MySQL is running,
If it is a 'localhost', then your IP address is 127.0.0.0

Python Database Application Programmer's Interface (DB-API):

Python Database Application Programmer's Interface (DB-API) is a standard interface for


accessing databases from Python. It provides a consistent way to interact with different
database systems, such as MySQL, PostgreSQL, SQLite, and Oracle.

Key Components of DB-API

Module Attributes: Provide information about the DB-API implementation, such as the API

g
level, thread safety, and parameter style.

or
Connection Objects: Represent a connection to a database. Used to create cursors and

manage transactions.
s.
te
da
Cursor Objects: Used to execute SQL statements and fetch results. Exceptions: Define
p

standard exceptions for handling errors.


uu

Basic Usage
an

Import the DB-API module. Ex import sqlite3


w

Establish a connection.
w

Ex connection sqlite3.connect('mydatabase db') Create a cursor:


w

Ex cursor connection.cursor() Execute SQL queries.

Ex cursor.execute("SELECT FROM mytable") Fetch results.

Ex: results cursor.fetchall() Commit or rollback transactions.

152 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Ex connection.commit() #or connection.rollback()

Close the cursor and connection. Ex cursor.close() connection.close()

Benefits of Using DB-API

Standardization: Ensures that code written for one database can be easily adapted to
another

Portability:Simplifies the process of switching between different database systems.

Consistency:Provides a uniform way to interact with databases, making code more readable
and maintainable.

Abstraction: Hides the specific details of the underlying database system, allowing

g
developers to focus on the application logic.

or
Q. Object Relational Managers (ORMS)

s.
ORM, or object-relational mapping, is a programming method used to bridge the gap
te
between object-oriented programming languages (like Python, Java, Ruby, C++, JavaScript,
da
C#, and many more) and relational databases (like PostgreSQL, MySQL, or SQLite).
Fundamentally, it acts as a translator, translating data between the database and the
p

application without any hitch. ORM enables developers to work with objects in their
programming language which are mapped to corresponding database entities, such as tables,
uu

views, or stored procedures.


an

OBJECT-RELATIONAL MAPPING PROCESS


w

Objects python php Java


w

Relational database TypeScript


w

N.NET

153 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Key Concepts of ORM:

Object-Oriented Paradigm: ORM focuses on OOP principles that data and behavior are
encapsulated within objects. In ORM, database entities are mapped to objects and
developers use objects to interact and manipulate data in a fairly easy way.

Mapping: The main purpose of ORM is object mapping to database tables and back. The
mapping is defined through the metadata which represents interconnections between the
corresponding database schemas. Metadata of ORM frameworks is used for the generation
SOL queries and management of data flow between the application and the database

CRUD Operations: ORM makes CRUD operations easier. Developers can perform
operations on objects in their programming language, the ORM framework takes care of
translation of the operations to their corresponding SQL statements for the underlying datab

g
ORMs Work:

or
s.
database tables. te
1. Define Objects/Classes: Developers define objects or classes that represent the structure of
da
the ORM automatically maps the obiect attributes to

2. ORM Handles the Mapping: The


p
uu

corresponding database columns and handles the translation between objects and SOL 3.
Interacting with Objects. Developers can then interact with the database data by using ter
an

objects and classes, as if they were interacting with regular objects within their application
queries
w
w

4. ORM Translates to SOL: The ORM internally translates the object operations into SOL .
and interacts with the database.
w

1) Entity Mapping:

The first initialization step in the Object-Relational Mapping (ORM) process identify entities
from the object-oriented model and match them with corresponding tables in the relational
database.

Developers specify objects or classes for business entities in their code and the ORM
framework manages the conversion of such entities into tables in databases.

Each feature in the class maps to a new column in the table, and instances of the class turn
into rows in the table.

2) Relationship Mapping:

154 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24


Having entities mapped the next important stage is to provide relations between them and
structuring the relational database schema accordingly.

ORM frameworks provide functions that enable us to represent the relationship between
entities like one-to-one, one-to-many, and many-to-many.

Such relationships are transformed into foreign kevs, which allow the data to be kept both
consistent and valid even when stored in tables that could be related.

3) Data Type Mapping:

Data mapping is the practice of an object-oriented model mapping the data type to the
database.

ORM frameworks handle the conversion of data types, that enable the objects of the

g
application to align with the data types.

or
It becomes the most important step, ensuring cohesion and preventing data type mismatches

s.
that will result in errors. te
4) Query Language:
da

ORM framework is usually a query language designed with object-oriented features for
p

interacting with the database.


uu

For example, Hibernate Package which is a Java-based ORM framework, makes use of
Hibernate Query Language (HQL).
an

Benefits of ORM
w
w

Abstraction of Database Complexity: ORM insulates the developers from the complexity of
SQL queries and database schema features. Illustration: Such abstraction enables
w

theprogrammers to concentrate on their application's logic and mechanics while avoiding


lower level database interactions

Portability: ORM ensures code poutability through abstraction between the application and
the database. Developers can switch between various database code changes since the
object-relational mapping framework deals with the details of database pe queries

Code Reusability: ORM boosts the cosde reusability by a classic way of relationship with
databases. Developers can use a single codebase with different databases which makes it
easier to maintain and scale applications

Maintenance and Scalability: ORM facilitates application maintenance via schema change
and updates management. Aside from that, it enables scalability due to the ability for
developers to optimize and fine-tune database interactions without major changes in
application code
155 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24
Q. Related Modules

Object-Relational Managers (ORMs) in Python are libraries that facilitate interaction


between object oriented code and relational databases. ORMs abstract away the
complexities of SOL, allowing developers to work with databases using Python objects. Here
are some popular ORM modules and

related concepts: Popular ORM Modules

a) SQLAlchemy: A powerful and flexible ORM that provides both a high-level ORAM and a
lower-level SQL toolkit. It supports multiple databases and offers features like declarative
mapping and relationship management.

b) Django ORM:Integrated with the Django web framework, it provides a simple and
intuitive way to interact with databases. It's well-suited for web development projects.

g
c) Peewee: A lightweight and simple ORM designed for ease of use. It's a good choice for

or
smaller. projects or when a minimalistic approach is preferred.

s.
d) PonyORM:A Python ORM that uses a generator-based query language, allowing for
te
concise and readable database interactions.
da

c) Tortoise ORM:A modern ORM that leverages asyncio for high-performance database
p

operations, making it suitable for asynchronous applications.


uu

f) SQLObject:A simple and lightweight ORM, that has been around for a while and is still
used in some projects.
an
w
w
w

156 | © www.anuupdates.org Strictly Copyrighted subject to AP IT Act 2021-24

You might also like