[Link].
, 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, Namespaces, Importing Modules,
Importing Module Attributes,
Module Built-in Functions, Packages, Other Features of Modules
UNIT-III
Regular Expressions: Introduction, Special Symbols and Characters, Res and Python
Multithreaded Programming: Introduction, Threads and Processes, Python, Threads, and the
Global Interpreter Lock, Thread Module, Threading Module, Related Modules
UNIT-IV
GUI Programming: Introduction, Tkinter and Python Programming, Brief Tour of Other GUIs,
Related Modules and Other GUIs
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) Server
UNIT-V
Database Programming: Introduction, Python Database Application Programmer's
Interface (DBAPI), Object Relational Managers (ORMs), Related Modules.
1 | © [Link] 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:
[Link](server side [Link] development, [Link],
[Link] scripting.
Q. Python Objects
Class: A class is a user-defined data type. It consists of data members
(variables) and member functions, which can be accessed and used by creating
an instance of that class. It represents 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.
2 | © [Link] 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 members) and behaviors (called functions).
An object is a runtime instance of a defined class. Each instance of
an object holds its own relevant data or value,
● In Python, an object can refer to anything that can have a name, such
as functions, integers, strings, floats, classes, methods, and modules. It
is a collection of data, and methods utilize that data.
Characteristics of Object
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.
It is typically represented by variables. During the execution of a program, the
state of an object may change frequently.
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 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=attribute
3 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
self.attribute2=attribute
2 #Method
4 | © [Link] 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:
def init (self, brand, model): #The init
method. [Link] =brand #Attribute
[Link]= model #Attribute
#Create an object (instance) of the
Car class my_car =Car("Toyota",
"Corolla")
#Access attributes
print(my_car.brand) # Output:
Toyota print(my_car.model) #
Output: Corolla 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.
5 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
6 | © [Link] 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
Ex: often.
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.
Ex:
b = 1.5
print(b, "is of type",
type(b)) Output: 1.5 is
of type
● Boolean Data Type:
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 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:
x =True y
= False
You can also use comparison operators to create Boolean values:
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
7 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
following are the standard or built-in data types in Python:
8 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
● Numeric
9 | © [Link] 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 different types as follows:
a) Int :It stores all the integer numbers. Moreover, these numbers can be
positive or negative For example, 1, -99, 10, 25, etc.
b) Float: This data type stores the real or floating type numbers. This means
that it stores all the numbers having decimal values. Moreover, they can be
negative or positive. For example, 4.0, -2.89, 3.45, etc.
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.
Ex:
a =150
print(a value", a)
b=20.846 print("b
value", b)
Output:
a value 150
b value 20.846
Sequence Data
Types
1. String Data Type:
10 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
● A group of one or more characters enclosed in a single, double, or
triple quote is called a string in python
11 | © [Link] 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: list['abcd', 786,2.231 print (list)
print (list[0])
Output: ['abcd', 786, 2.23] abcd
3. Tuple Data Type
● A tuple in Pythen is an ordered list of elements, just like a list.
● Tuples are not changeable, which is the only difference.
● Once created, tuples cannot be changed.
● In Python, items of a tuple are stored using parentheses ().
● In Python, we utilize the indes number to retrieve tuple items, just like with lists.
Ex:
tuple=('abcd,
786,223) print
(tuple)
print (tuple[0])
Output: (abcd, 786,
2.23) Abcd
12 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
13 | © [Link] 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:
dict = {}
dict['one'] ="This is
one" dict[2] ="This is
two" print (dict['one'])
print (dict[2])
Output: This is
one This is two
Boolean Data Type:
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.
14 | © [Link] 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.
● float: Represents floating-point numbers (numbers with decimal
points), e.g., 3.14,
-2.5, 0.0,
● complex: Represents complex numbers, c.g., 2+3j, 1-lj.
2. Sequence Types:
● str: Represents strings (sequences of characters), e.g., "hello", "world",
"123"
● list: Represents ordered, mutable sequences of items, e.g... ['a', 'b', 'c'].
● tuple: Represents ordered, immutable sequences of items, e.g.,
(1, 2, 3), ('a', 'b', 'c').
3. Mapping Type:
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.,
15 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
bytearray(b"x01\x02\x03').
16 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
6. Boolean Type:
bool: Represents truth values, either True or False.
7. Other Internal Types:
17 | © [Link] 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 object used for indexing.
7. None Type:
✔ NoneType: Represents the absence of a value, often used for
default values or to indicate that a variable has no value.
These internal types are fundamental to Python's functionality and are
used extensively in various programming tasks. They provide the building
blocks for creating more complex data structures and algorithms.
These data types can be further categorized based on their mutability:
✔ Mutable: Lists, Sets, Dictionaries, Bytearrays
✔ Immutable: Numbers, Strings, Tuples, Bytes
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
18 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
● Bitwise Operators
19 | © [Link] 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
* Multiplication a*b=200
/ Division b/a=0
% Modulus b%a=0
** Exponent a**b=10**20
// Floor division 9//2=4
Comparison Operators :Python Comparison operators compare the values on
either side of them and decide the relation among them. They are also called
Relational operators.
Operator Name Example
== 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
20 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Assignment Operators: Python Assignment operators are used to assign values
to variables Following is a table which shows all Python assignment operators.
21 | © [Link] 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
Operator Name Example
& AND a&b
l OR alb
~ NOT ~a
<< Zero fill left shift a<<3
>> Signed right shift a>>3
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.
Assume variable a holds 10 and variable b holds 20 then
Operator Name Example
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 a in b
finds a variable in
the specified
sequence ,false otherwise
22 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
not in Return true if it does not a not in b
finds a variable in the
23 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
specified sequence ,false
otherwise
24 | © [Link] 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 a is b
variable
are the same object and
false otherwise
is not Return true if both a is not b
variable
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 always present for use. These functions are known
as Built-in Functions. There are several built-in functions in Python which are
listed below:
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 argument can be an integer and floating-point
number. If the argument is a complex number, then, abs() retums its
magnitude.
Syntax:
abs(num) Ex :
x=-20
print('Absolute value of -20 is:',
abs(x)) Output :Absolute value of -20
is: 20
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
25 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
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])
26 | © [Link] 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.
Ex:
x-8
print(eval(x+1))
6) len(): The python len() function is used to return the length (the number of
items) of an object Ex
strA = 'Python' print(len(strA)) output 6
7) list(): The python list() creates a list in python.
Ex String= 'abcde'
print(list(String))
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:
27 | © [Link] 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
y = hex(x)
print (y)
Output: 0xe
10)max() Function: The Python max() function is used to retrieve the largest
element from the specified iterable. In general max is an operation where we
find the largest value among the given values. For example, from the values
10, 20, 75, 93 the maximum value is 93.
Syntax max(x, y, z)
Ex: print (“max (80, 100, 1000)":”, max(80, 100, 1000))
print ("max(-20, 100, 400)", max(-20,100, 400))
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
28 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
min(-20, 100, 400): -20
29 | © [Link] 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, such as the "unsupported operand type(s) for +" error.
Understanding the "Unsupported Operand" Error
In Python, the "unsupported operand type(s) for +" error occurs when you try
to perform an arithmetic operation, such as addition, on operands of
incompatible types. This error is commonly encountered when attempting to
add or concatenate objects of different data types, such as trying to add a
string and an integer.
Ex:
x=5
y= "LabEx"
z=x+y
In this case, the error occurs because you're trying to add an integer(x) and a
string (y), which are not supported operand types for the + operator.
The operator in Python has different meanings depending on the operand
types. For 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.
30 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex2:# Missing Required Discrete Values
31 | © [Link] 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 data types before performing the operation. You can use built-in
functions like int(), float(), or str() to convert the data types as needed.
Ex:
x=5
y=”10”
z=x+int(y)
print(z)
Output: 15
Separate Numeric and String Operations: If the operation involves both numeric and
string operands, you can separate the operations and perform them individually.
Ex:
x=5
y="LabE
x"
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.
32 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Python supports three types of numbers, including integers, floating-point
numbers and complex numbers.
33 | © [Link] 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
Long Integers:
L suffix is used for the representation of long integers in Python. Long integers
are used to store large numbers without losing precision.
I=99999999999L
Octal and Hexadecimal:
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 Python interpreter can recognize that we want
the value to be in base 8 and not in base 10.
Ex I = 11
I = 11 #Then in Octal we will
write print (1)
Output 9
Performing arithmetic Operations on int type:
Ex :#Addition
res 5+3 #Output: 8
#Subtraction
res-10-4 #
Output: 6
#Multiplication
34 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
res 7*6 #Output: 42
35 | © [Link] 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) Floating-point numbers;
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 number
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 float() function.
Ex:
a=3.14 # A positive
float b=-0.99 #A negative float
c=0.0 #A float value that represents zero
Performing arithmetic Operations on float
type: #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
36 | © [Link] 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)).
#Addition (complex)
res =( 3 + 4j + (1 + 2j) #output(4+6j)
res = (4+ 6j)-(2 + 3j)#output(3+3j)
#multiplication
res =(2+3j)*(1+4j)#output:(-
10+11j) #division
res =(8+6j)/(2+3j)3output:(2.0+0.0j)
#exponentiation
res=(1+j)***2 #output(0+2j)
#real and imaginary parts of a complex number
real=(3+4j).real#output:3.0
imag=(3+4j)imag #output:4.0
Q. Strings
Strings are one of the most fundamental data types in Python, representing
sequences of 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
37 | © [Link] 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
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
Ex
string 1="hello" #Output: hello
2. Concatenate Operator"+":
Two strings can be concatenated or joined using the operator in Python, as
explained in the below
example
code 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
38 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
the
39 | © [Link] 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.
● The "!=”operator returns Boolean True if two strings are not the same and
returns
Boolean False if two strings are the same.
Ex:
string1= "hello"
string2="hello, world"
string3= "hello, world"
string4="world"
print(string1==string4)
print(string2==string3)
Output:
Fals
Tru
5. Membership Operator "in" & "not in"
The membership operator searches whether the specific character is
part/member of a given input Python string.
40 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
● "a" in the string: Returns boolean True if "a" is in the string and returns
False if "a" is not in the
41 | © [Link] 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) print("t"
not in string1)
Output:
True
Fals
True
String Methods: Python provides numerous built-in methods for string
manipulation. Some commonly used methods include:
● len(); Returns the length of the string.
Ex
a
="Hello"
print(len(a))
Output :5
● lower(): Converts the string to lowercase
● upper(): Converts the string to
uppercase Ex:
42 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
txt= "Hello"
x=txt. upper()
43 | © [Link] 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=[Link]("welcome")
print(x)
Output :7
● replace(): Replaces a substring with another string
● split(): Splits the string into a list of substrings.
● join(): Concatenates a sequence of strings.
Q. Lists
A list is a collection of ordered and mutable elements enclosed in square
brackets || It can 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.
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)
44 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
45 | © [Link] 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:
list1=["apple", "banana",
"cherry" ] list2=[1.5, 7, 9, 3]
list3 =[True, False, False]
7. A list with strings, integers and boolean values:
Ex:
list ["abc", 34, True, 40, "male"]
Creating Lists
my_ list=[] #Empty list
numbers= [1, 2, 3, 4, 5] # List of integers
names= ["Alice", "Bob", "Charlie"] # List of
strings
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
46 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
47 | © [Link] 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:
list=[2,5,6,7]
[Link](8)
print(list)
Output: [2, 5, 6, 7, 8]
2. insert():
The insert() method can add an element at a given position in the list. Thus,
unlike 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 position, and the second argument specifies the
element to be inserted.
Ex
myList =[1,2,3]
[Link](3,
4)
[Link](4,
5) print(myList)
Output:
[1,2,3,4,5]
3. remove(): The remove() method removes an element from the list.
48 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Only the first occurrence of the same element is removed in the case of
multiple occurrences.
Ex:
49 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
myList
=[1,2,3]
[Link](
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, Le, lists with similar elements
Ex :
myList =[1, 2, 3, 4, 5, 6, 7]
print(min(myLis
t))
print(max(myLi
st))
Output :1,7
7. count(): The function count() returns the number of occurrences of a given
element in the list
Ex: myList= [1, 2, 3, 4, 3, 7, 3, 8, 3]
print([Link](3))
Output :4
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+yourL
ist)
Output: [1,2,3,4,5]
Features of Lists
50 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
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
51 | © [Link] 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.
Creating a Tuple
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 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 are lists, tuples,
or dictionaries
Ex:
num =(100, 35, 7, 21) # tuple with integer
values print(num)
my_tuple =(23.545, Hello, 'A' 785) #tuple with mixed
values print(my_tuple)
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")
52 | © [Link] 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 the desired element. Tuple concatenation is another tool you
can use to join the modified and original items together.
Ex:
tup1 =(16, 44.26);
tup2 =('abc',
'xyz');
tup3=tup1+tup2
; prin (tup3)
Output: (16,44.26, 'abc' 'xyz)
This code creates a new tuple called tup3 by combining two defined tuples, tupl
and tup2. It 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)
53 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
print("Deleted tuple:", deleted_tuple)
54 | © [Link] 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
tupl
e Ex
:
t1=(1,2,3,4,5,6)
print(5 in
t1) print(10
in t1)
Output:
True False
6. not in : It is also a membership operator and It returns true if a particular item
is not present in the tuple
Ex
t1=(1,2,3,4,5,
6)
#not in
operator
print(4 not in
11) print(10 not
55 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
in 11) Output
Fals
Tru
56 | © [Link] 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))
Output: 9
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.
Ex:
my_tuple =(5, 6, 7, 8,
9)
print(min(my_tuple))
Output: 5
4. sum() function: The sum() function is used to return the sum of all elements in a
tuple.
Ex: my_tuple =(1, 2, 3, 4, 5)
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)
57 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
print(count)
58 | © [Link] 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, list, etc.
Creating a Dictionary
In Python, it is easy to create a dictionary, add the items inside the curly braces
and assign them to a variable name. The items will be in the form of key, value
pairs, you need to 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.
59 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
24:280}
60 | © [Link] 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 [] and
the element's
key.
Ex:
#Accessing the age of
Alice alice_age=
ages["Alice"]
print(alice_age)
Adding Elements: To add a new key-value pair to a dictionary, you can use
square brackets [] and
assign a value to the new key:
In Python, the assignment opcrator (") is the most popular and straightforward
way to add 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)
61 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Updating Elements: To update an existing element, you can use the same
syntax: #Updating an element in the dictionary
62 | © [Link] 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 = [Link]("Alice")
print(ages)
print(alice_age)
Dictionary
Methods
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 below.
Methods Description
clear() Removes all the elements from the
dictionary
copy() Returns a shallow copy of the specified
dictionary
has_key() Returns true if the key exists in the
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
63 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
achieve this by employing a hash table for data storage, permitting constant-
time access to values, regardless of dictionary size.
64 | © [Link] 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.
● No duplicate elements. If try to insert the same item again, it
overwrites previous one.
● An unordered collection. When we access all items, they are accessed
without any specific order and we cannot access items using indexes
as we do in lists.
● 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.
● Mutable, meaning we can add or remove elements after their creation,
the individual elements within the set cannot be changed directly.
Syntax:
variable_name= {"string", value, number} OR variable_name =set([value,
value, value]) 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’}
65 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
2. Using Curly Braces:
employee_id = {12, 14,
16, 18}
66 | © [Link] 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.
Ex :A1 = {24, 35, 34, 45}
A2 = {24, 56, 35, 46}
A3 = {24, 35, 47, 56}
print([Link](A2, A3)) #Output: {34,35,45,46,47,24,56}
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 returned as a set.
Ex:
A1= {24, 35, 34, 45}
A2= {24, 56, 35, 46}
A3= {24, 35, 47, 56}
print([Link](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.
67 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
A1= {24, 35, 34, 45}
A2= {24, 56, 35, 46}
print([Link](A2))
print([Link](A1))
Output: {34,45}
{56,46}
68 | © [Link] 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
Q. Flow of Control
A program's control flow is the order in which the program's code executes.
The control flow of a Python program is regulated by conditional statements,
loops, and function calls.
Python has three types of control structures:
Sequential-default mode
Selection - used for decisions and branching
Repetition - used for looping, i.e., repeating a piece of code multiple times.
1. Sequential: Sequential statements are a set of statements whose execution
process happens 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.
69 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
70 | © [Link] 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
Ex:
i=10
if (i > 15):
print("10 is less than
15") print("I am Not in
if")
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.
71 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
72 | © [Link] 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:
if (condition-1):
if (condition-2):
……..
……..
else:
…….
…….
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")
73 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
elif b >c:
74 | © [Link] 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.
Ex:
lst=[1, 2, 3]
for i in range(len(1st)):
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
.
75 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
76 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
m=
5
i=0
while i <m:
print(i, end = "")
i=i+1
print("End")
Output :01234
End
Q. Truthiness
In Python, "truthiness" refers to how values are evaluated in a boolean
context, such as in if statements or boolean operations. Every object in Python
has a truth value, which is either True or False.
Default Truthiness:
By default, most objects are considered "truthy"
Empty collections (lists, tuples, dictionaries, sets, strings) are considered "falsy"
The
number zero (0) is considered "falsy”.
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).
77 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
If neither bool () nor len () are defined, the object is considered truthy.
78 | © [Link] 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 print(bool(None)) #
Output: False
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 desired logic.
Use Cases:
Truthiness is commonly used in conditional statements (if, elif, while)
to check if a value is "empty" or "zero"
It allows for more concise code, as you can directly use objects in
boolean contexts without explicit comparisons.
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:
79 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
numbers= [3, 6, 1, 8, 2, 9, 5]
80 | © [Link] 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
sorted_numbers.append(minimum)
#remove minimum from the numbers list
[Link](minimum)
print(sorted_numbers)
Output:[1,2,3,5,6,8,9]
Explanation:
Given 3 6 1 2 9 5
elements: 8
Step 1 : 3 6 8 2 9 5 1
Step 2 : 3 6 8 9 5 1 2
Step 3 : 6 8 9 5 1 2 3
Step 4 : 6 8 9 1 2 3 5
Step 5 : 8 9 1 2 3 5 6
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.
81 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
82 | © [Link] 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]
[Link]
()
print(numbe
rs)
OUTPUT: [1, 1,2,3,3,4, 5, 5, 5, 6, 91
83 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
84 | © [Link] 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)
print(sorted_numbers)
Output: [[Link].3,4,5,5,5,6.9]
Types of Sortings:
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
Advantages
We can swap the data elements without consumption of short-term
storage, It requires less space.
2) Merge Sort: Merge sort first divides the array into equal halves and then
combines them in a sorted manner.
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
85 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
them in their proper position.
Advantages
86 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
It is simple and easy to implement.
87 | © [Link] 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.
It lets you create clear, simple code on a single line as opposed to
several lines filled with loops in Python.
You can also add conditions to filter which elements should be included
in the new list.
List comprehension in Python is faster and more efficient than
traditional loops for creating lists.
It is great for transforming data, such as squaring numbers, filtering
even or odd numbers, or manipulating strings.
Syntax: mylist=[output/expression for item in iterable if
condition True] 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
88 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
89 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Example of Simple List Comprehensions in
Python def simplest_list_comp(ls):
90 | © [Link] 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.
Adding Some Conditions to Above Code-- Let us now add some conditions to
our previous code and check how it works.
Ex:
def simplest_list_comp(ls):
#adding a condition to check if
#the element is an odd or even number
mylist[i for i in Is if i % 2 = 0]
print("My list is:",mylist)
simplest list
comp([1,5,6,7,8,9,10,11,12]) 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):
91 | © [Link] 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
[Link]
(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
Aspect For loop List comprehension
syntax Requires multiple lines of code Uses a single line of code
performanc Generally slower due to more overhead Typically,its faster as its
e optimized internally
Code length It requires more lines It is more concise than a
loop
readability It can be more verbose and harder to More readable for simple
follow iterations
Use case Suitable for complex logic and multiple Best for simple
actions transformation or
filtering
flexibility More flexible for handling complicated Less flexible but great for
logic straightforward tasks
Advantages of List Comprehension
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
92 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Iterator: An iterator is an object which contains a countable number of values. The
iterator
93 | © [Link] 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.
94 | © [Link] 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
good example is taken, for it is considered a list.
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 sequential indexes that starts with 0.
Ex:
iterator_test= iter([10, 20, 30, 40,
50]) print(type(iterator_test))
print(next(iterator_test))
print(next(iterator_test))
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
95 | © [Link] 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.
Iterable
Iterable is also an object which can iterate over. It's generated by using the
_iter_() method. It's inherited from iterations. It is to be looped over or iterated
over with the help of a for loop used.
Examples of iterable are the objects like lists, tuples, sets, dictionaries, strings,
etc.. Iterable also says anything that you can loop over.
For Example:
1. # String as an
iterable for i in
PYTHON print(i)
2. # list as an
iterable for i in
[1, 2, 3,4]:
print(str(i*2)) Output:
1. P
Y
T
H
2. 2
96 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
4
6
97 | © [Link] 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.
diagra
m
Example 1:
#Program to print the Power of two up to the given number
def Power TwoGen(max=0): n=1 while n < max: yield 2** n n+=1 #Printing
the values stored in a
a Power TwoGen(6) for i in a:
print(i) Output:
24
8 16 32
Difference Between Iterators and Generators
Iterators generators
Iterators are the objects that use A generator is a function that
the next()method to get the produces or yields a sequence of
next value values using a
of the sequence yield statement
Classes aree used to implement Functions are used to implement the
the generators
iterators()
Every iterator is not a generator Every generator is an
iterator
Complex implementation of Generators in python are similar to
iterator protocols .i.e.,iter () code
and next () then do the custom iterator using
the yield statement
98 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Iterator in python are less Generators in python are more
memory memory
efficient efficient
99 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Non local variables are used in All the local variables are stored
iterator before
the yield statement .
100 | © [Link] 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 [Link], these files contain data in a readable
format for humans to
access.
Any text editor can be used to edit the plain text that they contain.
Text files can be handled in Python utilizing modes like a for
appending, w for writing, and r for reading.
2. Binary Files:
Unlike text files, binary files contain data like pictures, films, or
computer programs that are not readable by humans. .bin [Link] are
typical extensions for them.
Python handles similar to text files, binary files with the addition of a b
suffix, such as rb for reading binary files and wb for writing them.
File Objects:
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.
101 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
File Operations in Python
102 | © [Link] 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.
b) readline()-Reads one line at a time.
c) readlines-Reads all lines into a list.
Ex:
Using read() method
with open("[Link]", "r") as file:
content [Link]()
print(content)
Output :
Welcome to College
3.)write() Function: To write to a Python file, we need to open it in write mode
using the w parameter. To write data to a file, use the write() or writelines()
methods.
Ex:
with open("[Link]", "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
103 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
data loss and free up system resources.
104 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
file =open("[Link]", "w")
105 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link]("This is an example.")
[Link]()
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)
file-name: It specifies the name of the file to be opened.
access-mode: There are following access modes for opening a file:
Access Descrption
mode
“w” Write – opens a file writing, creates the file it doesnot
exist
“r” Read-default [Link] a file for reading error if the
file
doesnot exist
“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+” Open a file for updating,overwrite if the file exist
“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()
106 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
readline()
write()
107 | © [Link] 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 :[Link]()
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.
Syntax: [Link]([size])
Where 'size' specifies number of bytes to be read.
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() method two times, then we can get the first two lines of the file.
Syntax :[Link]()
write(): The write () method is used to write the content into file. To write some
text to a file, we need to open the file using the open method with one of the
following access modes.
w: It will overwrite the file if any file exists. The file pointer point at the
beginning of the file in this mode.
Syntax: [Link](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: [Link](list)
Here list This is the Sequence of the
strings. Ex:
f=open("[Link]", "w")
108 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link](["Python supports Files \n", "python supports
Strings."]) [Link]()
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:
[Link]()
[Link]
function open() to open a
file. method read() to read
a file. Ex:
f=open("[Link]", "r")
print([Link]())
print([Link]())
[Link]()
Output: 33
seek(): The seek() method sets and returns the current file position in a
file stream. Syntax:
[Link](offs
et) EX:
f= open("[Link]", "r")
print([Link](9))
109 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
print([Link]())
[Link]();
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 ([Link]), the mode with which the file was opened ([Link]),
whether the file is closed ([Link]), and a flag indicating whether an
additional space character needs to be displayed before successive data items
when using the print statement ([Link]).
File object attributes Description
[Link] 1 if file is closed ,0 otherwise
[Link] Access mode with which file was
opened
[Link] Name of file
[Link] 0 if space explicity
Example:
f=open ("[Link]",
"r") print([Link])
print([Link])
print([Link]
) [Link]()
print([Link])
Output:
[Link]
110 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
111 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
r
Fals
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.
These streams provide a way for the program to interact with the
external environment, such as the user's console or other programs.
The three standard files are:
Types of Standard Files
Standard Input (stdin)
This is the default input stream, typically connected to the user's keyboard.
It allows the program to receive input from the user. In Python, the input()
function reads data from stdin.
Represents the source of input for the program, typically the
keyboard. Accessed using [Link].
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 [Link] or the print() function.
Used to display information to the user or another
program Standard Error (stderr)
112 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
113 | © [Link] 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
[Link] object.
Represents the destination for error messages and diagnostics.
Accessed using [Link]
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:
import sys
#Reading from standard
input input_data=
[Link]()
print("You entered:", input_data) #Writing to standard output
[Link]("This is standard output'n") #Writing to standard error
[Link]("This is an error message\n")
Q. Command Line Arguments
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:
114 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
115 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
1. Using [Link]
2. Using getopt module
3. Using argparse module
a) Using [Link]:
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
print("Script Name is:",
[Link][0]) print("Arguments
are:", [Link][1:]) Command
Line Interface:
python generate [Link] 1
100 5 Output:
Script Name is generate_random.py
Arguments are:[1,100.5]
b) Using getopt Module:
The getopt module is a more powerful tool for parsing command line
arguments. It offers 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 [Link]([Link][1], "ho:", ["help", "output="])
except [Link]
as err print(err) # Process
options
116 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
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)
117 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Command Line Interface:
python [Link]-h
Output: Help Needed
Command Line
Interface:
python [Link] -0 5
Output:
Arguments Passed with -o Option:-5
c) Using Argparse Module :
Argparse is the recommended command-line parsing module in Python's
standard library. It's 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
import argparse
parser =[Link]()
parser.add_argument("--arguments", help="insert
argg") args =parser.parse_args()
print([Link]())
Command Line Interface:
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).
118 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
The os module provides us the methods that are involved in file processing operations
and
119 | © [Link] 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: [Link] ("current-name", "new-
name") Ex:
import os;
#rename [Link] to [Link]
[Link]("[Link]","[Link]
t") Removing the file -
remove():
The os module provides us the remove() method which is used to remove the
specified file. Syntax: [Link]("file-name")
Ex:
import os:
#deleting the file named
[Link]
[Link]("[Link]")
Creating the new directory - mkdir()
The mkdir() method is used to create the directories in the current working
directory Syntax: [Link]("directory-name")
Ex: import os;
#creating a new directory with the name new
[Link]("dirnew")
Changing the current working directory-chdir()
120 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
The chdir() method is used to change the current working directory to a specified
directory
121 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Syntax: [Link]("new-
directory") Ex:
import os;
#changing the current working directory to new
[Link]("dir2")
Get current working directory - getpwd():
This method returns the current working
directory Syntax. [Link]()
Ex:
import os;
#printing the current working
directory print([Link]())
Deleting directory - rmdir(): The rmdir() method is used to delete the specified
directory. Syntax. [Link]("directory name")
Ex:
import os;
#removing the new directory
[Link]("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: [Link](["path"])
Ex:
import os;
#list of files and directories in current working directory
122 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
print([Link]()) #list of files and directories in specified
path print([Link]("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
[Link]() or the with statement, which automatically closes the file.
Q. File Execution
Python is a well-known high-level programming language. The Python script is
a file 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...
Running Python Scripts in Terminal:
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 python include the GNOME Terminal, Konsole,
and macOS's Terminal.
On Windows, you can use the Command Prompt or PowerShell. You can find
the 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
123 | © [Link] 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 [Link] 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
Then, with the following command, you can make the script executable:
chmod +x script_name.py Now simply, type the below command to run
your script directly.
/script_name.py
How to Run Python on Windows
On Windows, Command Prompt can be used to run the Python scripts with ease. Just
open Command Prompt and use the cd command to go to your script's directory:
ed path\to\your script
Then, run your script with: python script_name.py
Ensure Python is added to your system PATH to run it from any
directory 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([Link])
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
124 | © [Link] 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 print("Error
Division by zero!")
In this example, the code within the try block raises a ZeroDivisionError
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 instead of abruptly terminating. In this example, the code
within the try block raises a ZeroDivisionError 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 instead of
abruptly terminating.
Different Types of Exceptions in Python:
1. SyntaxError: When the interpreter comes across a syntactic problem in the
code, such as a misspelled word, a missing colon, or an unbalanced pair of
parentheses, this exception is raised.
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.
125 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
7. AttributeError: When an attribute or method is not present on an object, such as
126 | © [Link] 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.
[Link]: 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 User-Defined Exceptions Types of
Exceptions in Python
Built-in Python Exceptions
Built-in exceptions are the standard exceptions defined in Python. These
exceptions are raised wher the program encounters an illegal operation like
semantic errors.
These built-in exceptions are generated either by the interpreter or the built-in
functions of Python The interpreter returns a string indicating the error code and
the related information whenever an exception is raised.
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.
127 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
8. NameError: raised when a variable is not found in the local or global scope.
128 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
9. MemoryError: raised when programs run out of memory.
[Link]: 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.
[Link]: raised by the parser when the Python syntax is wrong.
[Link]: occurs when there is a wrong indentation.
[Link]: raised when the interpreter detects an internal error.
Ex: FileNotFoundError
This exception is raised when a file or directory is requested, but the specified
file or directory does not exist. When a file that should be read, accessed, or
retrieved doesn't exist, Python throws the FileNotFoundError exception.
#Python program for
FileNotFoundError try:
with open(" [Link]") as f:
contents =[Link]()
except FileNotFoundError as e:
print(" A file not found error occurred: ", e)
Output :A file not found error occurred. [Errno 2] No such file or directory: [Link]'
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.
129 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
130 | © [Link] 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)
[Link] = args
#Additional methods and attributes can be
added here Ex :
#Create a user defined exception class that inherits from
Exception class. Class MyException(Exception):
pass
try:
raise MyException("My exception") #Exception value stored
in m. except MyException as m:
print(m)
Output: My exception
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.
131 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Enhanced Error Handling: User-defined exceptions allow developers to
handle errors in a more granular and specific manner. By defining
custom exception classes,
132 | © [Link] 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.
Try and Except Statement-Catching Exceptions: Try and except statements are
used to catch and handle exceptions in Python. Statements that can raise
exceptions are wrapped inside the try block and the statements that handle the
exception are written inside except block.
Ex:
a=[1,2, 3]
try:
print ("Second element = %d" %
(a[1])) print ("Fourth element = %d"
%(a[3]))
except:
print ("An error occurred")
133 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Output: Second element =
2 An error occurred
134 | © [Link] 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.
Synta
x try:
#statement(s)
except
IndexError:
#statement(s)
except
ValueError:
statement(s)
Ex :def
fun(a):
if a <4 :
b=a/(a-3)
print("Value of b =",
b) try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and
135 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Handled") except NameError:
print("NameError Occurred and Handled") #Output: ZeroDivisionError Occurred
and Handled
136 | © [Link] 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") else:
print (c)
AbyB(2.0,
3.0)
AbyB(3.0, 3.0)
Output: -5.0
a/b result in
Finally Keyword in Python: Python provides a keyword finally, which is always
executed after the try and except blocks. The final block always executes after
the normal termination of the try block or after the try block terminates due to
some exception. The code within the finally block is always executed.
Syntax:
try:
#Some Code.....
except:
#optional block
#Handling of exception (if required)
else:
137 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
#execute if no exception
138 | © [Link] 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') Output:
Can't divide by zero This is always executed
Q. Context Management
A context manager in Python is a design pattern that facilitates the allocation
and deallocation of resources, ensuring that certain tasks are performed before
and after a 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.
Context managers are useful for managing files, network
connections, database connections, and any other resources that
require setup and cleanup.
They promote cleaner, more readable, and more robust code by
ensuring resources 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
139 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
140 | © [Link] 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('[Link]', 'r') as file:
ex :
with open (‘[Link]’,’r’) as file:
content = [Link]()
Here, after executing the block of code inside the 'with statement, the file is
automatically closed, even if an exception occurs within the block.
Context management protocol consists of two special methods:
1. . enter () is called by the with statement to enter the runtime context.
2. . exit () is called when the execution leaves the with code block.
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:
141 | © [Link] 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:
Ex :
class MyContextManager:
def enter (self):
#Initialization or resource
allocation return self
def exit (self, exc_type, exc_value, traceback):
#Cleanup or resource
deallocation Pass
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()
142 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
yield resource
143 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link]()
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.
Automatic Resource Handling: Context managers automatically
manage resource allocation and deallocation, ensuring that resources
like files, network connections, and appropriate releasing of locks after
usage. This is known as automatic resource handling.
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.
Less Boilerplate Code: Context managers simplify and ease the
maintenance of the codebase by removing the boilerplate code
required for resource management.
Q. Exceptions as Strings
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:
144 | © [Link] 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:
#Code that might raise an
exception raise "File not found"
except "File not found":
print("Caught a string exception: File not found")
It's important to note that this approach is outdated and using class-based
exceptions is now the standard practice in Python.
Q. Raising Exceptions
The raise keyword is used to raise an exception. You can define what kind of
error to raise, and the text to print to the [Link] is a keyword (case-
sensitive) in python, it is used to raise an Exception/Error with a customized
message and stops the execution of the programs.
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"
145 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
146 | © [Link] 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:
raise Exception("This is a general
exception") Ex:
def divide(a, b):
if b==0:
raise ValueError("Cannot divide by
zero") return a/b
try:
result divide(10, 0)
except ValueError
as e:
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
147 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
to provide more detailed context about the error condition.
Ex:
148 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
class InvalidAgeError(Exception):
def init (self, age, message="Age must be between 18 and 100"):
[Link] = age
[Link]==
message super(). init
([Link]) def
set_age(age):
if age 18 or age > 100:
raise
InvalidAgeError(age)
print(f"Age is set to
{age}") try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {[Link]}.{[Link]}")
Output: Invalid age: 150. Age must be between 18 and 100
Advantages of the raise keyword
It helps us raise error exceptions when we may run into situations
where execution 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.
149 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
The assert statement is used to determine whether or not a given condition is true. If
the
150 | © [Link] 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:
assert <condition>
assert <condition>, <error message>
1) assert statement has a condition and if the condition is not satisfied the
program will stop and give AssertionError
2) assert statement can also have a condition and a optional error message. If
the condition is not satisfied assert stops the program and gives
AssertionError along with the error message.
Flowchart :
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
151 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
became
152 | © [Link] 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
AssertionError List is empty.
We passed a non-empty list mark2 and also an empty list mark1 to the avg()
function and we got output for mark2 list but after that we got an error
AssertionError: List is empty. The 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.
Use Python Assert Statement
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 for using assert.
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 throughout your code.
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
153 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
154 | © [Link] 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:
a=5
c=a+
print("Sum
=",c) Output:
Traceback (most recent call last):
File "[Link]", line 2, in
c=a+b
NameError: name 'b' is not defined
ZeroDivisionError: Occurs when a number is divided by zero.
Ex:
a=5
b=0
print(a/b)
Output:
Traceback (most recent call
last): File "[Link]",
line 3, in print(a/b)
ZeroDivisionError: division by zero
155 | © [Link] 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
Traceback (most recent call last):
File "[Link]", line 2, in
b- int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: "abc"
Index Error: Occurs when we request for an out-of-range index for sequence
Ex:
Is=['e','java', 'python']
print("list item is ",ls[5])
Output:
Traceback (most recent call last):
File "[Link]", 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")
156 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
print("The age is:",dic["age"])
157 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Output:
Traceback (most recent call last):
File "[Link]", 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("[Link]")
print(fn)
Output:
Traceback (most recent call last);
File "[Link]", line
1, in fn-
open("[Link]")
FileNotFoundError: [IOError] No such file or directory: '[Link]’
Q. Creating Exceptions
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 customize it to add features based on your
specific needs.
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):
158 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
159 | © [Link] 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):
[Link]= message
super(). _init
([Link])
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.
class ValueError(Exception):
def init (self, message="Invalid value"):
[Link] =message
super(). init
([Link])
Raise the Exception: Once you have defined a custom exception, you
can raise it in your code to signify specific error conditions. Raising
user-defined exceptions involves using the raise statement, which can
be done with or without custom messages and attributes.
Syntax :
raise
ExceptionType(args) Ex
def process data(value):
if not isinstance(value, int):
raise ValueError("Input must be an
160 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
integer") return value *2
Handle the Exception:
Handling user-defined exceptions in Python refers to using "try-except" blocks to catch
and
161 | © [Link] 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):
def init (self, age, message "Age must be between 18
and 100"): [Link] = age
[Link]= message
super(). init
([Link]) def
str (self):
return f" {[Link]}provided age:{[Link]}"
def set_age(age):
if age 18 or age > 100:
raise
InvalidAgeError(age)
print(f"Age is set to
{age}") try:
set _age(150)
except InvalidAgeError as e:
print(f"Invalid age: ([Link]) ([Link])")
Output Invalid age: 150. Age must be between 18 and 100
Q. Exceptions and the sys Module
162 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
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
163 | © [Link] 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
[Link]
Output :’3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021,
15:26:21) [Link]:
In Python, this includes a list of arguments (command prompt) supplied to the
script. If you write len([Link]), you'll get a count of how many arguments
there are. [Link] is used by people who work with command-line arguments.
The name of the script is referred to as [Link][0]
Ex:
import sys
print([Link][0
])
print('Number of arguments present=',
len([Link])) print('Total argument list:',
str([Link]))
Output:
[Link]
Number of arguments present
= 1 Total argument list:
['[Link]'] [Link]:
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
[Link]
Output: [", "C:\\Python39\\Lib\\idlelib']
164 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
165 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link]: This maxsize function returns the variable's
greatest integer Ex :import sys
[Link]
Output: 9223372036854775807
Important Functions In The SYS Module
[Link](): 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):
print("ERROR. Odd one is present in the even
list! ") [Link]()
else:
print("Pure Even
List") list=
[2,4,5,6,8,10]
is_even(lis
t) is_
even(list)
Output: ERROR: Odd one is present in the even list!
2. [Link](): This method allows you to adjust the default
encoding for strings in the Python environment.
Ex:
import sys
[Link]('UTF
8')
3. [Link]():
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([Link]
(i)) Output: 28
166 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
167 | © [Link] 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 [Link]:
if 'quit' [Link]():
break
print(f'Input (words)")
print("Exit!!")
Output:
Hello
Input:
Hello Bye
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 [Link], then to the screen. Let's understand this in a better
way from the example that is given below:
168 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex
import sys
[Link]('Learn_To_Cod
e') 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.
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 the files with the py extension. A Python module can
also include runnable code.
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.
Features of Modules.
Allows code reusability
Provides flexibility in organizing code logically and segments a larger
problem into small manageable files.
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"
#[Link] 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
169 | © [Link] 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.
170 | © [Link] 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
We have already discussed that modules contain functions and classes. But
apart from functions and classes, modules in Python can also contain variables
in them. Variables like tuples, lists, dictionaries, objects, etc.
Example
#This is variables module
## this is a function in module def
factorial(n): if n1||n=0:
return 1 else:
return n factorial(n-1)
## this is dictionary in module power
= { 1:1,
2:4,
171 | © [Link] 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
Global Namespace: This is the top-level namespace that contains all the
names defined at the module level.
Local Namespace: This is the namespace that contains the names defined
within a function or a class.
Built-in Namespace: This is the namespace that contains the built-in functions,
types, and constants provided by the Python interpreter.
Accessing Namespaces
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 my_function in a module my_module, you would use
my_module.my_function.
Ex
## 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()
172 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
173 | © [Link] 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:
a) globals(): Returns a dictionary of the names in the global namespace
b) locals(): Returns a dictionary of the names in the current local namespace.
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 keyword: Allows you to assign a different name to an
imported object. f)_name_variable: Provides information about the current
namespace.
Ex :
## Example of namespace manipulation import math as m
print(globals()) ### Access global namespace print(locals()) ## Access local
namespace print(dir(m)) ## Access namespace of the math module print(name)
## Access the current namespace name
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.
174 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
175 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
import math pie [Link]
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)
Output: 3.141592653589793
Importing Built-in Modules
Python provides many built-in modules that can be imported directly without
installation. These modules offer ready-to-use functions for various tasks, such
as random number generation, math operations and file handling.
Ex
import random
#Generate a random number between 1 and 10 res [Link](1, 10)
print("Random Number:", res) Output: Random Number: 9 Importing Modules with
Aliases
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.
176 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
177 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex
import math as m
#Use the alias to call a function result [Link](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 *
print(pi) #Accessing the constant 'pi' print(factorial(6)) # Using the factorial function
Output: 3.141592653589793
720
Advantages:
It becomes easy to trace back the modules for code check. Easy to use
and very straightforward.
If the project is moved to a different path, still the imports will remain the same.
Q. Importing Module Attributes
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.
178 | © [Link] 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 [Link] as shown below.
Example: Set name_ def SayHello(name):
print ("Hi ()! How are you?".format(name))
name="SayHello" And check the name attribute now.
Example: Set name_ import hello
print(hello_name) #"Say Hello
The value of the_name_ attribute is_main_ on the Python interactive shell and
in the [Link] module.
Example:_main_ print(name)
Example: [Link]
Q. Module Built-in Functions
→ OS module:
This module has functions to perform many tasks of operating system.
mkdir(): We can create a new directory using mkdir() function from os module.
179 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
import os [Link]("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 [Link]("d:\\temp")
◯● listdir(): The os module has listdir() function which returns list of all files in
specified
directory. [Link]("c:\\
Users")
['acer', 'All Users', 'Default', 'Default User', '[Link]', 'Public']
statistics module This module provides following statistical functions:
mean() calculate arithmetic mean of numbers in a list Ex :
import statistics [Link]([2,5,6,9])
Output 5.5
median() returns middle value of numeric data in a list. For odd items in list, it
returns value at (n + 1) / 2 position. For even values, average of values at n/2
and (n / 2) + 1 positions is returned. Ex
import statistics [Link]([1,2,3,8,9]) Output :3
180 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
mode(): returns most repeated data point in the list. Ex :
import statistics [Link]([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 [Link]([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.
time(): This function returns current system time in ticks. The ticks is number of
seconds elapsed after epoch time i.e. 12.00 am, January 1, 1970.
Ex [Link]()
Output 1544348359.1183174
localtime(): This function translates time in ticks in a time tuple notation. Ex tk =
[Link]() [Link](tk) Output :
time.struct_time(tm_year = 2018 , tm_mon-12, tm_mday 9, tm_hour = 15 , tm_min =
11 , tm_sec=25,
tm_wday-6, tm_yday-343, t m\ isdst=0)
asctime(): This functions readable format of local time Ex
181 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
tk = 1 [Link]()
tp = 1 [Link](tk)
[Link](tp) Output: 'Sun Dec 9
15:11:25 2018'
ctime(): This function returns string representation of system's current time Ex
[Link]() Output: 'Sun Dec 9 15:17:40 2018"
sleep(): This function halts current program execution for a specified duration in
seconds. Ex [Link]()
Output: 'Sun Dec 9 15:19:14 2018' Ex
[Link](20) [Link]()
Output 'Sun Dec 9 15:19:34 2018' sys module:
This module provides functions and variables used to manipulate different
parts of the Python runtime environment.
[Link](): This method allows you to adjust the default encoding
for strings in the
Python environment. Ex:
import sys [Link]("UTF8") [Link]():
After using this function, the size of an object in bytes is returned. Any object
can be used as an
object.
182 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
183 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
import sys i-3 print([Link](i))
Output 28
[Link]: 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.
A package is a directory of Python modules that contains an additional init py
file, which distinguishes a package from a directory that is supposed to contain
multiple Python scripts. Packages can be nested to multiple depths if each
corresponding directory contains its own_ init_.py file.
Diagram
The file/folder structure should be as shown below:
PackageDemo [Link] [Link] [Link]
mypackage init py [Link] [Link]
To Create Package in Python
Creating packages in Python allows you to organize your code into
reusable and manageable modules. Here's a brief overview of how to
create packages:
184 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
185 | © [Link] 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 named mypackage, you would import its function like this:
from [Link] import greet.
Distribution: If you want to distribute your package for others to use, you can
create a [Link] file using Python's setuptools library. This file defines
metadata about your package and specifies how it should be installed.
Ex:
step1:
#[Link]
def average(x,y): val= (x+y)/2 return
val step2:
#[Link] def rectangle(w,h):
area wh return
area step3 :
#[Link]
from [Link] import rectangle print ("Area", rectangle(10,20)) from
[Link] import average
print ("average:", average(10,20)) Output: Area: 200
186 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
187 | © [Link] 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.
UNIT-III
Regular Expressions and Multithreaded Programming
Q. Special Symbols and Characters Regular Expressions:
regular expression is a special sequence of characters that helps you match or
find other strings or sets of strings, using a specialized syntax held in a pattern.
Regular expression are popularly known A
as regex or regexp. Lisually, such patterns are used by string-searching
algorithms for "find" or "find and replace" operations on strings, or for input
validation.
● Large scale text processing in data science projects requires
manipulation of textual data. The regular expressions processing is
supported by many programming languages including Python.
● 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.
188 | © [Link] 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.
*to match 0 or more occurences of the preceding pattern.
+ to match I or more occurences of the preceding
pattern. Metacharacters
Metacharacters are special characters with a defined meaning. They are used to
perform actions such as aggregation, pairing, reiteration, and pairing the
search pattern.
Metacharacters are crucial for mastering Python regular expressions and are
used in functions of the 're' module.
189 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex:
impon re
pattern a-zA-Z] string "123 abcXYZ matches
[Link](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" of a calculation or operation. It is not a reserved keyword
or built-in function, but rather a 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.
"res" as a variable name:
● Common Practice: Programmers often use "res" as a variable name to
store the result of a function call, a calculation, or any other operation.
● Meaning:"res" is short for "result," and it clearly indicates that the
variable will hold the outcome of a process.
● Readability: This convention improves the readability of code by
making it easy to understand what a variable represents
"re" module for Regular Expressions:
● 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:
190 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
191 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
WsCube Tech explains that the [Link]() function can find the first match of a
pattern in a string
Other functions:
The "re" module includes functions like [Link](), [Link](), and [Link]() 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:
A thread is an entity within a process that can be scheduled for execution.
Also, it is the smallest unit of processing that can be performed in an OS
(Operating System). In simple 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 of a
process!
A decad contains all this information in a Thread Control Block (TCB): Thread
Identifier: Unique id (TID) is assigned to every new thread
Stack pointer: Points to thread's stack in the process. Stack contains the local
variables under thread's scope.
Program counter, a register which stores the address of the instruction currently
being executed by thread.
Thread states can be running, ready, waiting, start or done. Thread's register
set: registers 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!")
192 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
threading. Thread(target-hello_world)
[Link]() 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
Registersegsters Registers Stack
Stack Thread Thread
Single-headed Process Multireaded Process Advantages of Threading
Threads improve the overall performance of a program. Threads increases the
responsiveness of the program Context Switching time in threads is faster.
Threads share the same memory and resources within a process.
Communication is faster in threads.
Processes:
193 | © [Link] 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.
A process is less efficient in terms of communication. Every process runs in its
own memory. A process does not share data with each other A
Thread
Thread means a segment of a process A thread takes less time to
terminate It takes less time for creation
It takes less time for context switching
Thread is more efficient in terms of communication. Threads
share memory Threads share data with each other
Q. Python Threads
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.
194 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
195 | © [Link] 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!")
[Link](target-hello_world)
[Link]() Output hello world Life Cycle of a
Thread
There are multiple states of the thread in a lifecycle as mentioned below:
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 yet to be run and has not started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state.
In this state, a 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 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 CPU so that
other threads can run
3. Blocked: The thread will be in blocked state when it is trying to acquire a
lock but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when acquires the lock
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ỢাT 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:
196 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
197 | © [Link] 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 concurrency
issues.
CPU
Python Code
thread thread2y thread
→ CPU
Interpreter Lock
CPU GIL Work:
The GIL works by acquiring and releasing a lock around the Python-interpreter
A thread 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 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.
198 | © [Link] 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
on different CPU cores. 2. I/O-bound Tasks: The GIL is less of an issue for I/O-
bound tasks (tasks that spend a lot of time waiting for input/output operations).
Threads can release the GIL, when waiting for 1/0 operations, allowing other
threads to run. This makes threading a viable option for applications that are
I/O-
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 threads. This can help avoid GIL-related issues while
still achieving concurrency.
Advantages of the GIL
Simplifies memory management and makes it easier to write thread-safe
code. Provides a level of safety by preventing race conditions and
deadlocks.
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
199 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Thread Handling Modules in Python Python's standard library provides two main
modules for managing threads: thread and threading.
200 | © [Link] 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 [Link] 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.
syntax thread start new thread(function, args[, kwargs])
Ex: This example demonstrates how to use the thread module to create and
run threads. 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 exiting.
import thread import time
def print_name(name, *arg) print(name,
arg) name "Tutorialspoint."
thread start_new_thread(print name, (name, 1)) thread start new
thread(print_name, (name, 1, 2)) [Link](0.5)
Output: Tutorialspoint... I
Tutorialspoint 12 The Threading
Module
201 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
202 | © [Link] 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.
In addition to the methods, the threading module has the Thread class that
implements threading. The
methods provided by the Thread class are as follows -run() The run() method is
the entry point for a thread.
start() The start() method starts a thread by calling the run method. join([time])
The join() waits for threads to terminate.
isAlive() The isAlive() method checks whether a thread is still executing.
getName() The getName() method returns the name of a thread. setName() The
setName() method sets the name of a thread.
Starting a New Thread Using the Threading Module
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
203 | © [Link] 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
204 | © [Link] 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 [Link](target=print_name, args (name, 1, 2))
[Link]()
[Link]()
#Wait for threads to complete [Link]()
[Link]()
print("Threads are finished...exiting") Output:
Tutorialspoint... 1
Tutorialspoint... 12
Threads are finished...exiting
UNIT-IV
GUI Programming
Q. Tkinter and Python Programming
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
205 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
206 | © [Link] 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.
Tkinter Methods
Tk() To create a main window in Tkinter, we use the Tk() class. The syntax for
creating a main
window is as follows:
Syntax root tk. Tk(screenName=None, baseName=None, className=Tk', useTk=1)
screenName: This parameter is used to specify the display name. This parameter
can be used to set the base name of the application.
baseName:
className: We can change the name of the window by setting this parameter
to the desired 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:
207 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
import tkinter
208 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link]() #creating the application main window.
209 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
[Link]("Welcome") #title of main window [Link]("400x300") #size of main
window [Link]() #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
. Canvas: This widget can be used for drawing shapes, images, and custom graphics.
5 6. Frame: This acts as a container widget that can be used to group other
widgets together 7 Checkbutton: A checkbox widget used for creating toggle
options on or off
. 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.
8. Radiobutton: This is used to create Radio buttons. 9 Fonts, Colors,
Images in Tkinter of For Ex:
The choice of fonts, colors, and images can make a significant impact on the
user experience and the overall aesthetic appeal of an application.
Fonts Colors
Choose color
Dialog
210 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
211 | © [Link] 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
[Link]() [Link]("My First GUI") #Create a label
widget [Link](window, text="Hello, Tkinter!")
[Link]() #Create a button widget
button [Link](window, text="Click Me") [Link]()
#Run the main loop (to display the window and handle events) [Link]()
Q. Brief Tour of Other GUIs
Python has plenty of frameworks for developing GUIs that deliver a high-quality
user experience without a hefty price tag. Here are some of the most popular
Python GUI frameworks used by developers.
1. PyQt5
Riverbank Computing's PyQt package is built around the Qt framework, which is a
cross-platform framework used for creating a plethora of applications for various
platforms.
The PyQt5 package includes a detailed set of bindings for Python based on the
V5 version of the Qt application framework.
212 | © [Link] 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 contributor Fredrik Lundh created Tkinter to equip modern developers
with a standard Interface to the Tk GUI toolkit with its Python bindings.
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.
3. Kivy
Written using a mix of Python and Cython. Kivy is an open-source GUI
framework Va building user interfaces encompassing multi-touch applications.
It implements a natural user interface (NUI) a kind of interface where the user
naturally usually kept invisible learns about the various interactions provided by
a user interface that's
The most common use of the Kivy GUI framework can be seen in Android and
applications. Other widespread implementations of the framework can be seen
in the user interfaces of Linux, Windows, Raspberry Pi and macOS devices.
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.
213 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
wxPython allows Python developers to create native user interfaces that add zero
additional
214 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
overhead to the application. The cross-platform capabilities of wxPython allow
deployment to
215 | © [Link] 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 handled by the hardware acceleration achieved via OpenGL and GPU
shaders to deliver smooth and graphic-rich visuals.
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.
Key features:
Ideal for building touch-based devices.
Uses OpenGL to support video decoding, compositing and other capabilities.
Possesses features like text alignment, animation support and GPU effects,
6. PySimpleGUI
PySimpleGUI is designed for Python newbies to get into GUI development
without spending 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
216 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
217 | © [Link] 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 in web, terminal and Windows GUI
Ideal for quickly building prototypes and supporting application maintenance.
8. Wax
Just like wxPython was a wrapper for the wxWidgets GUI toolkit, the Wax GUI
framework is a more developer-friendly wrapper of wxPython.
Like other popular frameworks, Wax is implemented as an extension module
for Python. And it also supports building cross-platform applications.
The idea behind Wax is to offer developers simpler access to the Python
elements and objects for building GUIs by removing the low-level aspects of
wxPython.
Key features:
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
218 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Web Surfer Program Works
219 | © [Link] 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.
Set a random sleep interval between page loads to simulate natural browsing
behavior.
The Benefits of Using the Web Surfer Program
a) Time-saving: Instead of manually searching for web pages and clicking on
each result, the program automates the process, saving you time and effort.
) Convenience: The program serves the web pages to you in a tabbed browser,
allowing you to b sit back and watch them like you're watching TV
c) Passive browsing: By automatically loading each web page in a new tab,
the program creates a passive browsing experience where you can
effortlessly browse through different results.
d) Research efficiency: The program is particularly useful for researchers who
need to quickly scan through multiple web pages throughout the day
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
220 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
search string join([Link][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=[Link] #Get the results
page response [Link](search_query) #Check if the page was fetched
successfully if [Link] code [Link] results page
[Link] else:
print('Error in fetching the web page") [Link](1)
3. Parsing the Results Page with Beautiful Soup
Next, we need to parse the HTML of the results page to extract the links. This
can be achieved using the
Beautiful Soup Ex:
from bs4 import BeautifulSoup
#Create a Beautiful Soup object with the results page HTML soup
page BeautifulSoup(results_page, '[Link]') #Extract the links from
the soup page links soup page.find_all('a') #Print out the links
221 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
222 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
for link in links:
print([Link]('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):
#Extract the links from the soup page links soup_page.find_all('a')
#Create a list of the href attributes extracted_links [[Link]('href') for link in
links] return extracted links
5. Opening the Links in New Browser Tabs
Finally, we can open cach link in a new tab using the
webbrowser Ex import webbrowser
#Open each link in a new browser tab
for link in extracted links: webbrowser.open_new_tab(link) Web client
definition: Q Creating Simple Web Clients
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:
223 | © [Link] 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
[Link] says-
Advanced Browser Features: Some web browsers offer advanced features
beyond basic browsing. such as developer tools, built-in scraping capabilities, or
extensions that enhance functionality NordVPN says.
Specialized Web Applications: Web-based applications that offer advanced
features, such as virtual desktop environments, remote access software, or
collaborative tools [Link] says.
Key Features of Advanced Web Clients:
Automation: Many advanced clients automate tasks, such as data extraction or
website testing.
Programmability: Some clients allow for custom scripting or programming to enhance
their functionality.
Extensive Capabilities: They offer a wider range of features than basic web
browsers, 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 [Link] 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
224 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
tasks like indexing websites, offline browsing, or accessing services through
web service clients.
225 | © [Link] 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:
Advanced web development often utilizes frameworks like React. Angular, and
[Link] to create complex and interactive applications.
These frameworks provide tools for building reusable components, managing
application state, and handling client-side logic.
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.
3. Examples of Advanced Clients: a
) Crawlers (Web Robots): These programs systematically explore and download
web pages for indexing search engines, archiving, or data extraction.
b) Oftine Browsing Tools: Programs that download web pages and create a
local mirror of the site for c)
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):[Link] 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
226 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
227 | © [Link] 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 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
sends it to the webserver, and the CGI programs return output to the
webserver based on the input that the client-server provides.
Common Gateway Imerface (CGI) provides a standard for peripheral gateway
programs to interface with the data servers like an HTTP server
The programming with CGf is written dynamically, which generates web-
pages responding to the input from the user of the web-pages interacting with
the software on the server
CGI Architecture
Diagram Common Gateway Interface Works:
The following common gateway diagram helps to understand how CGt works
when a user 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 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
228 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
229 | © [Link] 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 both user and provider by processing and selecting
the appropriate forms that match the selection criteria.
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 employed to serve as a gateway and use
appropriate programing language to read the information, format, and share it
with the client.
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, images, plain text to sometimes audio.
Features of CGI
CGf is utilized to create simple shell scripts and interactive application They
are well defined with a set of rules
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.
230 | © [Link] 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:
Make sure your web server (Apache, Nginx, etc.) has been configured properly
for handling CGL scripts; usually, this involves enabling Cils within the server
configuration file and setting up the
appropriate directory.
3. Write the Script:
Use some lext editor to create a new file for your script. Typically, the
extension reflects the language used (pl for perl, py for python)
Write script code that handles requests and generates responses. Ensure it starts
with the correct shebang line, depending on what language was chosen.
4. Set Permissions:
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:
231 | © [Link] 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.
In CGI programming, HTTP headers provide additional information about the
response to the client web browser. Some of the essential HTTP headers that
are commonly used in CGI programming include:
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.
2. Content-Length: This header specifies the size of the response body in
bytes. This is important for the client browser to know how much data to
expect and when the response is complete
3. Location: This header redirects the client to a different URL. It is
commonly used in conjunction with the 3xx HTTP status codes, such as
301 (Moved Permanently) or 302 (Found).
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.
232 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Passing Info using GET Method
233 | © [Link] 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-
[Link] 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.
CGI Environment Variables using Python
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 response. You can access the CGI
environment variables in Python using the os module.
This module provides
an environment dictionary that contains the current environment variables. For
example, you can access the REQUEST_METHOD variable, which specifies the
HTTP method of the request, using the following code:
import os [Link]["REQUEST_METHOD"] CGI environment variables
There are many other CGI environment variables that you can access in this
way. Some of the common ones include:
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.
234 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
235 | © [Link] 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 [Link]() c[L]-35 c['data'] = 'Fri 8 Apr
2016' print(c) Set-Cookie: L-35
Set-Cookie: data="Fri 8 Apr 2016" Password Encryption
We can use cookies for login names and passwords. For security purposes, we store
only the encrypted passwords.
A secure hash algorithm is often called a trapdoor function, as it is
computationally infeasible 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.
The server encrypts the password before sending it to the client. The
authentication happens by comparing encrypted passwords.
A session with the hashlib module is illustrated below. from hashlib import shal
m'this is me' hshal ([Link]())
<shal HASH object @ 0x1019a53f0> [Link]()
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.
236 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
237 | © [Link] 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([Link],
587) [Link]()
(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 tag with the file type will create a "Browse"
button.
Ex
<html>
<body>
<form enctype="multipart/form-data" action="save_file.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</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
238 | © [Link] 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("[Link]", "rb") [Link]();
print str
#Close opend file [Link]()
Q. Web (HTTP) Servers
A web server is actually a network application, running on some machine,
listening on some port.
Web server is a computer where web contents are stored.
A web server serves web pages to clients across the internet or an intranet
It hosts the pages, scripts, programs and multimedia files and serve them using
HTTP, a protocol
designed to send files to web browsers.
Apache web server, IIS web server. Nginx web server, Light Speed web server
etc are the common examples of web servers.
Types
There are two types of web servers-
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
239 | © [Link] 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 ([Link]), 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 the TCP/IP suite of protocol, it
establishes the connection using a combination of cable media and wireless
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 waiting
for the response. The server on the other side process the requests, prepare the
response, establishes the connection again and send back to response.
Again inform a HTTP message to the client when the two computer is
completely disconnect, that is the big general.
HTTP Protocol
It stands for Hyper Text Transfer Protocol.
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.
240 | © [Link] 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 [Link] 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 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
e all
UNIT-V
Database Programming
Q. Python Database Application Programmer's Interface (DBAPI) Database:
A database is basically a collection of structured data in such a way that it can
easily be retrieved, managed and accessed in various ways. Relational
databases are the most popular database system which includes the following:
MySQL
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.
241 | © [Link] 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 [Link] connect() [Link]() Cursor execute()
MySQL Connector Python Connection request connected B
result data 6 MYSQL
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 with the following components:
MySQL server
All available connectors MySQL Workbench MySQL
Notifier MySQL Sample Databases
parameters required to connect to the database:
Username- It is simply the username you give to work MySQL server with, the Default
242 | © [Link] 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 [Link]
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 level, thread safety, and parameter style.
Connection Objects: Represent a connection to a database. Used to create
cursors and manage transactions.
Cursor Objects: Used to execute SQL statements and fetch results. Exceptions:
Define standard exceptions for handling errors.
Basic Usage
Import the DB-API module. Ex import sqlite3
Establish a connection.
Ex connection [Link]('mydatabase db') Create
a cursor: Ex cursor [Link]() Execute SQL
queries.
Ex [Link]("SELECT FROM mytable") Fetch
results. Ex: results [Link]() Commit or
rollback transactions.
243 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
244 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
Ex [Link]() #or [Link]()
Close the cursor and connection. Ex [Link]()
[Link]() 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 developers to focus on the application logic.
Q. Object Relational Managers (ORMS)
ORM, or object-relational mapping, is a programming method used to bridge the
gap between object-oriented programming languages (like Python, Java, Ruby,
C++, JavaScript, 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 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, views, or stored procedures.
OBJECT-RELATIONAL MAPPING PROCESS
Objects python php Java
Relational database TypeScript
[Link]
245 | © [Link] 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
ORMs Work:
database tables.
1. Define Objects/Classes: Developers define objects or classes that represent the
structure of the ORM automatically maps the obiect attributes to
2. ORM Handles the Mapping: The
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 objects and classes, as if they were
interacting with regular objects within their application queries
4. ORM Translates to SOL: The ORM internally translates the object operations
into SOL . and interacts with the database.
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.
246 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
2) Relationship Mapping:
247 | © [Link] 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 application to align with the data types.
It becomes the most important step, ensuring cohesion and preventing data
type mismatches that will result in errors.
4) Query Language:
ORM framework is usually a query language designed with object-oriented
features for interacting with the database.
For example, Hibernate Package which is a Java-based ORM framework, makes
use of Hibernate Query Language (HQL).
Benefits of ORM
Abstraction of Database Complexity: ORM insulates the developers from the
complexity of SQL queries and database schema features. Illustration: Such
abstraction enables 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
248 | © [Link] 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.
c) Peewee: A lightweight and simple ORM designed for ease of use. It's a
good choice for smaller. projects or when a minimalistic approach is
preferred.
d) PonyORM:A Python ORM that uses a generator-based query language,
allowing for concise and readable database interactions.
c) Tortoise ORM:A modern ORM that leverages asyncio for high-
performance database operations, making it suitable for asynchronous
applications.
f) SQLObject:A simple and lightweight ORM, that has been around for a while
and is still used in some projects.
249 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24
250 | © [Link] Strictly Copyrighted subject to AP IT Act
2021-24