Python-Programming-by-Edu-Desire AKTU
Python-Programming-by-Edu-Desire AKTU
Programming
e
This pdf is only designed for B.Tech students of all Engineering Collage affiliated
with Dr APJ Abdul Kalam Technical University.
ir
This pdf provides help in the exam time for a quick revision in sorting the time.
es Compiled by
Sanjeev Yadav
D
u
Ed
Edu Desire
Computer & Technology
Follow me
Edu Desire 1
DETAILED SYLLABUS
Unit Topic
e
2
Representation.
Loops: Purpose and working of loops , While loop including its
ir
working, For Loop , Nested Loops , Break and Continue.
3
es
Strings : Length of the string and perform Concatenation and
Repeat operations in it. Indexing and Slicing of Strings.
Python Data Structure : Tuples , Unpacking Sequences , Lists ,
Mutable Sequences , List Comprehension , Sets , Dictionaries
Higher Order Functions: Treat functions as first class Objects ,
D
Lambda Expressions.
Edu Desire 2
Unit-1
Introduction to Python Programming
Introduction:
● Python is an interpreted, object-oriented, high-level programming
language.
● Python is a powerful multipurpose programming language created
by Guido van Rossum.
● It has a simple and easy-to-use syntax, making it a popular
first-choice programming language for beginners.
e
● Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need to compile your program before
ir
executing it. This is similar to PERL and PHP.
browsers to games.
Ed
Edu Desire 3
● A broad standard library: Python's bulk library is very portable
and cross-platform compatible with UNIX, Windows, and
Macintosh.
e
customize their tools to be more efficient.
ir
● Databases: Python provides interfaces to all major commercial
databases.
● Plan and Design: Once you understand the problem, you can plan
and design a solution. Break down the problem into smaller,
manageable tasks. Decide on the data structures, algorithms, and
overall program structure.
Edu Desire 4
e
ir
es
● Test and Debug: After writing the code, test it thoroughly to
ensure it works as expected. Identify and fix any errors or bugs
(debugging) that may arise during testing.
D
● Refactor and Optimize: In this stage, you review your code and
make improvements. Optimize the code for better performance,
readability, and maintainability. Refactor the code if necessary to
u
Python IDE:
● A Python IDE, or Integrated Development Environment, is a
software application that provides a variety of tools to help you
write, run, and debug Python code.
● IDEs typically include a code editor, a debugger, and a console
window. They may also include features like code completion,
syntax highlighting, and linting.
Edu Desire 5
Here are some of the most popular Python IDEs:
e
● Visual Studio Code: Visual Studio Code is a popular code editor
that can be used for Python development. It offers a variety of
features, including code completion, syntax highlighting, linting,
ir
and debugging. It is a good choice for developers who want a
powerful code editor with a wide range of features.
es
● Thonny: Thonny is a Python IDE that is designed for beginners. It
is a simple, easy-to-use IDE that provides a variety of features to
help beginners learn Python.
D
Remark: Which IDE is right for you depends on your needs and
preferences. If you are a beginner, I recommend starting with IDLE or
Thonny. If you are an experienced developer, you may want to use a more
powerful IDE like PyCharm or Visual Studio Code.
u
How to interact with Python Programs: Here are some ways to interact
Ed
● Standard Input/Output:
1. Python programs can use the input() function to prompt the
user for input.
Edu Desire 6
2. The program waits for the user to type something and press
Enter, then it can process the input and provide an output
using print() statements.
3. This allows for interactive communication between the user
and the program within the command line.
e
user-friendly interaction with your Python program.
● Web Interface:
ir
1. Python can also be used to create web applications using
frameworks like Django or Flask.
2. These frameworks enable you to build web interfaces where
es
users can interact with your Python program through a web
browser.
● File Input/Output:
D
1. Python programs can read input from files and write output
to files. You can use functions like open() to open a file, read
its contents, and process the data within your program.
2. Similarly, you can write output to files using open() with
appropriate file modes and write methods.
u
● API Integration:
Ed
Edu Desire 7
Elements of Python: Here are some key elements of Python explained.
● Variables:
1. Variables are like containers that store values.
2. In Python, you can create a variable and assign a value to it
using the assignment operator (=).
3. For example, name = "John" assigns the value "John" to the
variable name.
4. Variables allow you to store and manipulate data in your
programs.
● Data Types: Data types represent the kind of data a variable can
hold. Python has several built-in data types, including:
e
1. Strings: Used to store text or characters, such as "Hello" or
'Python'.
2. Numbers: Used to store numeric values, like integers (5) or
ir
floating-point numbers (3.14).
3. Booleans: Used to represent true (True) or false (False)
values.
es
4. Lists: Used to store multiple values in an ordered sequence.
5. Dictionaries: Used to store key-value pairs, where each value
is associated with a unique key.
6. Tuples: Similar to lists, but their elements cannot be
D
modified once created.
Edu Desire 8
3. Break and continue: Control flow statements that alter the
normal execution of loops.
● Functions:
1. Functions are reusable blocks of code that perform a specific
task.
2. They help organize code and make it more modular.
3. You can define your own functions in Python using the def
keyword and call them whenever needed.
e
pre-written code to perform specific tasks.
2. These libraries save time and effort by providing
ready-to-use functions and classes.
ir
3. Examples include the math module for mathematical
operations and the datetime module for working with dates
and times.
es
Note: These are just a few of the fundamental elements of Python.
Understanding and utilizing these elements will give you a solid
foundation for writing Python programs and solving various problems.
D
Type Conversion: Type conversion, also known as type casting, is the
process of converting the data type of a value into a different data type.
In Python, there are two types of type conversion:
u
Edu Desire 9
4. bool(): Converts a value to a Boolean.
integer_number = 123
float_number = 1.23
e
print("Value:",new_number)
print("Data Type:",type(new_number))
ir
Output:
Value: 124.23
es
Data Type: <class 'float'>
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output:
Edu Desire 10
Key Points to Remember
1. Type Conversion is the conversion of an object from one data type
to another data type.
2. Implicit Type Conversion is automatically performed by the
Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
user.
5. In Type Casting, loss of data may occur as we enforce the object to
a specific data type.
e
Expressions in Python:
● An expression is a combination of operators and operands that is
ir
interpreted to produce some other value.
● In any programming language, an expression is evaluated as per
the precedence of its operators.
● If there is more than one operator in an expression, their
es
precedence decides which operation will be performed first.
Example:
u
# Constant Expressions
Ed
x = 15 + 1.3
print(x)
Output:
16.3
2. Arithmetic Expressions:
● An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis.
● The result of this type of expression is also a numeric value.
● The operators used in these expressions are arithmetic operators
like addition, subtraction, etc.
Edu Desire 11
Operators Syntax Functioning
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
e
// x // y Quotient
ir
% es x%y Remainder
** x ** y Exponentiation
Example:
D
Let’s see an exemplar code of arithmetic expressions in Python:
# Arithmetic Expressions
x = 40
u
y = 12
add = x + y
Ed
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output:
52
28
480
Edu Desire 12
3.3333333333333335
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
e
Output:
25
ir
4. Floating Expressions: These are the kind of expressions that produce
floating point numbers as a result of all computations and type
conversions.
es
Example:
# Floating Expressions
D
a = 13
b=5
c=a/b
print(c)
u
Output:
Ed
2.6
5. Relational Expressions:
● In these types of expressions, arithmetic expressions are written on
both sides of the relational operator (>, <, >=, <=).
● Those arithmetic expressions are evaluated first, and then
compared as per relational operator and produce a boolean output
in the end.
● These expressions are also called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
Edu Desire 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions:
● These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions.
e
● For example, (10 == 9) is a condition if 10 is equal to 9.
● As we know it is not correct, so it will return False.
ir
● Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often.
Example:
Let’s have a look at an exemplar code :
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
Edu Desire 14
print(T)
Output:
False
True
True
Example:
# Bitwise Expressions
e
a = 12
x = a >> 2
ir
y = a << 1
print(x, y)
Output:
es
3 24
D
8. Combinational Expressions: We can also use different types of
expressions in a single expression, and that will be termed as
combinational expressions.
Example:
u
# Combinational Expressions
a = 16
Ed
b = 12
c = a + (b >> 1)
print(c)
Output:
22
Edu Desire 15
Operator Precedence:
● Operator Precedence simply defines the priority of operators that
which operator is to be executed first.
● Here we see the operator precedence in Python, where the operator
higher in the list has more precedence or priority:
1 Parenthesis ()[]{}
2 Exponentiation **
e
Unary plus or minus,
ir
3 -a , +a , ~a
complement
5
esAddition & Subtraction + –
D
6 Shift Operators >> <<
8 Bitwise XOR ^
Ed
9 Bitwise OR |
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
Edu Desire 16
14 Logical Operators and, or, not
# Multi-operator expression
e
a = 10 + 3 * 4
ir
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
es
print(c)
D
Output:
22
52
22
u
Python Operators:
Ed
1. Arithmetic Operators:
● Arithmetic operations between two operands are carried out
using arithmetic operators.
● It includes the exponent (**) operator as well as the +
(addition), - (subtraction), * (multiplication), / (divide), %
(remainder), and // (floor division) operators.
Edu Desire 17
Consider the following table for a detailed explanation of arithmetic
operators.
Operator Description
e
It returns the quotient after dividing the first
/ (divide) operand by the second operand. For example, if a =
ir
20, b = 10 => a/b = 2.0
Operator Description
Edu Desire 18
If the value of two operands is not equal, then the
!=
condition becomes true.
e
<
the condition becomes true.
ir
3. Assignment Operators: The right expression's value is assigned to
the left operand using the assignment operators.
es
The following table provides a description of the assignment operators.
Operator Description
D
It assigns the value of the right expression to the left
=
operand.
Edu Desire 19
It divides the value of the left operand by the value of the
right operand and assigns the reminder back to the left
%=
operand. For example, if a = 20, b = 10 => a % = b will be
equal to a = a % b and therefore, a = 0.
e
bit by the bitwise operators.
ir
Consider the case below.
Operator Description
es
A 1 is copied to the result if both bits in two
& (binary and) operands at the same location are 1. If not, 0 is
copied.
D
The resulting bit will be 0 if both the bits are zero;
| (binary or)
otherwise, the resulting bit will be 1.
^ (binary xor)
1, else it will be 0.
Ed
Edu Desire 20
The following logical operators are supported by Python.
Operator Description
e
If an expression a is true, then not (a) will be false and vice
not
versa.
ir
6. Membership Operators: The membership of a value inside a
Python data structure can be verified using Python membership
es
operators. The result is true if the value is in the data structure;
otherwise, it returns false.
Operator Description
D
If the first operand cannot be found in the second
in operand, it is evaluated to be true (list, tuple, or
dictionary).
u
Operator Associativity:
● The term "operator associativity" refers to the order in which
operators of the same precedence are evaluated when they appear
consecutively in an expression.
● In Python, most operators have left-to-right associativity, which
means they are evaluated from left to right.
However, there are a few exceptions
Edu Desire 21
● Left-to-Right Associativity:
1. Arithmetic Operators: +, -, *, /, %, //, **
2. Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
3. Bitwise Operators: &, |, ^, <<, >>
4. Comparison Operators: ==, !=, >, <, >=, <=
5. Logical Operators: and, or
● Right-to-Left Associativity:
1. Exponentiation Operator: **
2. Unary Operators: - (negation), + (unary plus), ~ (bitwise NOT)
e
It's important to note that associativity only comes into play when
operators have the same precedence. If operators have different
precedences, the one with higher precedence is evaluated first regardless
ir
of associativity.
unexpected results.
Ed
Edu Desire 22
Unit-2
Conditional Statements & Python Loops
e
2. if...else statement
3. if...elif...else statement
ir
1. Python if statement:
● The if statement evaluates condition.
es
● If condition is evaluated to True, the code inside the body of if is
executed.
● If condition is evaluated to False, the code inside the body of if is
skipped.
D
Syntax:
if condition:
# body of if statement
u
Ed
Example:
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.')
Edu Desire 23
print('The if statement is easy')
Output:
Number is positive.
The if statement is easy
e
If the condition evaluates to True
● the code inside if is executed
ir
● the code inside else is skipped
Syntax:
if condition:
# block of code if condition is True
D
else:
# block of code if condition is False
u
Ed
Edu Desire 24
Example:
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')
Output:
e
Positive number
This statement is always executed
ir
3. Python if...elif...else Statement:
es
● The if...else statement is used to execute a block of code among two
alternatives.
● However, if we need to make a choice between more than two
alternatives, then we use the if...elif...else statement.
D
Here,
● If the condition1 evaluates to true, code block 1 is executed.
● If condition1 evaluates to false, then condition2 is evaluated.
● If condition2 is true, code block 2 is executed.
● If condition2 is false, code block 3 is executed.
u
Syntax:
Ed
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Edu Desire 25
e
ir
Example:
number = 0
if number > 0:
es
print("Positive number")
D
elif number == 0:
print('Zero')
else:
print('Negative number')
u
Output:
Zero
This statement is always executed
Edu Desire 26
Syntax:
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
Example:
number = 5
e
# outer if statement
if (number >= 0):
# inner if statement
ir
if number == 0:
print('Number is 0')
Output:
u
Number is positive
Ed
x=5
Edu Desire 27
y=3
result = x + y * 2 # Multiplication is performed before addition
print(result)
Output: 11
name = "Alice"
message = "Hello, " + name + "!"
e
print(message)
ir
3. Boolean Expressions: Boolean expressions evaluate to either True or
False based on logical operations or comparisons. For example:
x=5
es
y=3
is_greater = x > y # Comparison expression
D
print(is_greater)
Output: True
def square(x):
return x ** 2
Output: 16
x=5
Edu Desire 28
y=3
result = (x + y) * 2 # Expression with parentheses
print(result)
Output: 16
e
Float Representation in Python:
● In Python, floating-point numbers are represented using the float
ir
data type.
● The float type represents real numbers with a fractional
component.
es
● The float representation in Python follows the IEEE 754 standard
for floating-point arithmetic.
● It uses a fixed number of bits to store the sign, exponent, and
mantissa (fractional part) of the floating-point number.
D
Here are a few important things to know about float representation in
Python:
Syntax: Floats are written using decimal notation with a decimal point.
u
They can also include the exponent notation using the letter "e" or "E" to
indicate powers of 10. For example:
Ed
x = 3.14
y = 2.5e-3 # 2.5 x 10^(-3)
1. Floating-Point Precision:
● Floating-point numbers have limited precision due to the finite
number of bits used to represent them.
● As a result, some numbers cannot be represented exactly, leading
to small rounding errors. For example.
x = 0.1 + 0.2
print(x)
Edu Desire 29
2. Floating-Point Arithmetic:
● Floating-point arithmetic in Python follows the rules of the IEEE
754 standard.
● It includes operations such as addition, subtraction, multiplication,
and division.
● However, due to the limited precision, there can be unexpected
results. For example.
x = 0.1
y = 0.2
z = 0.3
print(x + y == z)
e
Output: False (due to rounding errors)
ir
3. Special Float Values: Python includes special float values to represent
certain conditions:
● float('inf'): Positive infinity
es
● float('-inf'): Negative infinity
● float('nan'): Not-a-Number (used for invalid or undefined
operations)
D
4. Precision Control:
● Python provides various functions and modules, such as round(),
math, and decimal, to control the precision of float values or
perform more precise calculations when needed. For example
u
x = 0.1 + 0.2
rounded_x = round(x, 2) # Round to 2 decimal places
Ed
print(rounded_x)
Output: 0.3
Python Loops:
● In computer programming, loops are used to repeat a block of code.
● For example, if we want to show a message 100 times, then we can
use a loop. It's just a simple example; you can achieve much more
with loops.
Edu Desire 30
There are 3 types of loops in Python:
1. For Loop
2. While Loop
3. Nested Loop
e
Output:
Swift
ir
Python
Go
JavaScript
es
● In the above example, we have created a list called languages.
● Initially, the value of language is set to the first element of the
array,i.e. Swift, so the print statement inside the loop is executed.
D
● language is updated with the next element of the list, and the print
statement is executed again. This way, the loop runs until the last
element of the list is accessed
Flowchart:
Edu Desire 31
Example: Loop Through a String
for x in 'Python':
print(x)
Output:
P
y
t
h
o
n
e
Python for Loop with Python range()
● A range is a series of values between two numeric intervals.
ir
● We use Python's built-in function range() to define a range of
values. For example:
es
# use of range() to define a range of values
values = range(4)
# iterate from i = 0 to i = 3
D
for i in values:
print(i)
Output:
0
u
1
2
Ed
Edu Desire 32
Output:
Hello
Hi
Hello
Hi
Hello
Hi
Python for loop with else: A for loop can have an optional else block.
The else part is executed when the loop is exhausted (after the loop
iterates through every item of a sequence). For example:
e
digits = [0, 1, 5]
ir
for i in digits:
print(i)
else:
es
print("No items left.")
Output:
0
D
1
5
No items left.
2. Python while Loop: Python while loop is used to run a block code
u
while condition:
# body of while loop
Here,
1. A while loop evaluates the condition
2. If the condition evaluates to True, the code inside the while loop is
executed.
3. condition is evaluated again.
4. This process continues until the condition is False.
5. When condition evaluates to False, the loop stops.
Edu Desire 33
Flowchart:
e
ir
Example: Python while Loop
es
# program to display numbers from 1 to 5
i=i+1
Output:
Ed
1
2
3
4
5
age = 32
Edu Desire 34
while age > 18:
print('You can vote')
Python While loop with else: In Python, a while loop may have an
optional else block.
Here, the else part is executed after the condition of the loop evaluates to
False.
counter = 0
e
counter = counter + 1
else:
print('Inside else')
ir
Output:
Inside loop
Inside loop
es
Inside loop
Inside else
D
3. Nested Loop: Nested loops in Python refer to the concept of having
one loop inside another loop. This allows you to iterate over elements in a
hierarchical or multidimensional structure, such as nested lists or
matrices.
u
Example:
Edu Desire 35
Output:
apple red
apple yellow
apple blue
banana red
banana yellow
banana blue
cherry red
cherry yellow
cherry blue
e
Here are some examples of different star patterns you can create
using loops in Python:
ir
1. Square Star Pattern:
size = 5
for i in range(size):
for j in range(size):
es
print("*", end=" ")
print()
D
Output:
*****
*****
*****
u
*****
*****
Ed
Output:
*
**
***
****
*****
Edu Desire 36
3. Inverted Right Triangle Star Pattern:
for i isize = 5
n range(size, 0, -1):
for j in range(i):
print("*", end=" ")
print()
Output:
*****
****
***
**
e
*
ir
size = 5
for i in range(size):
for j in range(size - i - 1):
print(" ", end="")
es
for k in range(2 * i + 1):
print("*", end="")
print()
D
Output:
*
***
*****
u
*******
*********
Ed
Edu Desire 37
print("*", end="")
print()
Output:
*
***
*****
*******
*********
*******
*****
***
e
*
ir
Control flow Statement: In Python, break and continue are control flow
statements that allow you to alter the behavior of loops.
1. Break statement:
es
● The break statement is used to exit or break out of a loop
prematurely.
● When the break statement is encountered within a loop, the loop is
D
terminated, and the program execution continues with the next
statement after the loop.
Here's an example that uses break in a for loop to find a specific number
in a list and stop the loop once it is found:
u
target = 7
print("Loop finished")
Output:
1
2
3
Edu Desire 38
4
5
6
Number found!
Loop finished
2. Continue statement:
● The continue statement is used to skip the rest of the current
iteration of a loop and move to the next iteration.
● When the continue statement is encountered within a loop, the
remaining statements in the loop body are skipped, and the loop
proceeds with the next iteration.
e
Here's an example that uses continue in a for loop to skip printing even
numbers:
ir
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output:
u
1
3
Ed
5
7
9
Loop finished
Edu Desire 39
Unit-3
Function & Python Data Structure
e
Part of Function: A function typically consists of several parts:
ir
1. Function Definition: The function definition is where you define the
name of the function and specify any input parameters (arguments) it
es
requires.
Example:
D
def greet(name):
print("Hello, " + name + "!")
2. Function Body:
u
● The function body contains the block of code that gets executed
when the function is called.
● It performs the desired task or computation. The body is indented
Ed
Example:
def greet(name):
print("Hello, " + name + "!")
# Additional code in the function body
print("Welcome to our program!")
3. Parameters (Arguments):
● Parameters are placeholders for values that are passed into the
function when it is called.
● They allow you to provide input values to the function. Parameters
are listed inside the parentheses in the function definition.
Edu Desire 40
Example:
def greet(name):
print("Hello, " + name + "!")
Example:
e
def add_numbers(a, b):
return a + b
ir
5. Function Call:
● The function call is where you invoke or execute the function with
specific arguments (input values) to perform its task.
es
● You use the function name followed by parentheses, with
arguments (if any) inside the parentheses.
Example:
D
greet("Alice")
def function_name(arguments):
# function body
Ed
Return
Here,
● def - keyword used to declare a function
● function_name - any name given to the function
● arguments - any value passed to function
● return (optional) - returns value from a function
Example:
def greet():
print('Hello World!')
Edu Desire 41
Here, we have created a function named greet(). It simply prints the text
Hello World!.
This function doesn't have any arguments and doesn't return any values.
def greet():
print('Hello World!')
e
# call the function
greet()
ir
Example:
def greet():
print('Hello World!')
es
# call the function
greet()
D
print('Outside function')
Output:
Hello World!
u
Outside function
Ed
1. Default Arguments:
● Default arguments allow you to assign default values to parameters
in a function definition.
● If an argument is not provided when calling the function, the
default value is used.
Edu Desire 42
● Default arguments are helpful when you want to provide a common
value that is used most of the time but can be overridden if needed.
Example:
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
e
print( "Passing only one argument" )
function(30)
ir
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
es
Passing only one argument
number 1 is: 30
D
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
u
2. Keyword Arguments:
● Keyword arguments allow you to specify arguments by their
Ed
Example:
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
Edu Desire 43
function( 50, 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
e
number 2 is: 50
ir
# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
es
# calling function with two values
D
result = add_numbers(5, 4)
Output:
u
Sum: 9
Ed
For example:
def add_numbers():
sum = 5 + 4
Here, the sum variable is created inside the function, so it can only be
accessed within it (local scope). This type of variable is called a local
variable.
Edu Desire 44
1. Local Variables
2. Global Variables
Example:
def greet():
# local variable
e
message = 'Hello'
print('Local', message)
ir
greet()
es
# try to access message variable
# outside greet() function
print(message)
D
Output:
Local Hello
NameError: name 'message' is not defined
Here, the message variable is local to the greet() function, so it can only
u
function.
To fix this issue, we can make the variable named message global.
Example:
# declare global variable
message = 'Hello'
Edu Desire 45
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Output:
Local Hello
Global Hello
This time we can access the message variable from outside of the greet()
e
function. This is because we have created the message variable as the
global variable.
ir
# declare global variable
message = 'Hello'
es
Now, message will be accessible from any scope (region) of the program.
Python Strings:
D
● In computer programming, a string is a sequence of characters.
● For example, "hello" is a string containing a sequence of characters
'h', 'e', 'l', 'l', and 'o'.
● We use single quotes or double quotes to represent a string in
Python.
u
Example:
Ed
name = "Python"
print(name)
Edu Desire 46
Output:
Python
I love Python.
1. Indexing: One way is to treat strings as a list and use index values.
Example:
greet = 'hello'
e
# access 1st index element
print(greet[1])
ir
Output:
"e"
es
2. Negative Indexing: Similar to a list, Python allows negative indexing
for its strings.
D
Example:
greet = 'hello'
Output:
Ed
"e"
Example:
greet = 'Hello'
Output:
"ell"
Edu Desire 47
Note: If we try to access an index out of the range or use numbers other
than an integer, we will get errors.
Example:
message = 'Edu Desire'
message[0] = 'E'
print(message)
Output:
e
TypeError: 'str' object does not support item assignment
ir
Example:
message = 'Edu Desire'
es
# assign new string to message variable
message = 'Hello Friends'
D
prints(message);
Output:
prints "Hello Friends"
u
Example:
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Output:
Never gonna give you up
Never gonna let you down
Edu Desire 48
Python String Operations: There are many operations that can be
performed with strings which makes it one of the most used data type in
Python.
Example:
str1 = "Hello, world!"
str2 = "I love Python."
e
str3 = "Hello, world!"
ir
print(str1 == str2)
Example:
greet = "Hello, "
Ed
name = "Jack"
# using + operator
result = greet + name
print(result)
Output:
Hello, Jack
Example:
greet = 'Hello'
Edu Desire 49
# iterating through greet string
for letter in greet:
print(letter)
Output:
H
e
l
l
o
e
Python String Length: In Python, we use the len() method to find the
length of a string.
ir
Example:
greet = 'Hello'
es
# count length of greet string
print(len(greet))
Output:
D
5
Methods Description
Ed
Edu Desire 50
split() splits string from left
e
Example:
ir
name = 'Cathy'
country = 'UK'
es
print(f'{name} is from {country}')
Output:
Cathy is from UK
D
Python Data Structure: Python provides several built-in data structures
to efficiently store and manipulate collections of data.
u
Python List:
Ed
Edu Desire 51
Lists have several important characteristics and support various
operations:
1. Accessing Elements:
● You can access individual elements in a list using indexing.
● Indexing starts from 0, so the first element is at index 0, the second
element is at index 1, and so on.
● Negative indexing allows you to access elements from the end of
the list.
Example:
my_list = [1, 2, 3, 4, 5]
e
print(my_list[0])
print(my_list[-1])
ir
Output:
1
5
es
2. Modifying Elements: Lists are mutable, meaning you can change the
value of individual elements or modify the list itself.
D
Example:
my_list = [1, 2, 3, 4, 5]
my_list[2] = 'a'
print(my_list)
u
Output:
[1, 2, 'a', 4, 5]
Ed
my_list.append(6)
print(my_list)
Output:
[1, 2, 'a', 4, 5, 6]
Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4])
Edu Desire 52
Output: [2, 3, 4]
Example:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
concatenated_list = list1 + list2
print(concatenated_list) #Output: [1, 2, 3, 'a', 'b', 'c']
e
repeated_list = list1 * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
ir
length = len(my_list)
print(length) # Output: 5
print(2 in my_list)
es # Output: True
5. List Methods: Lists have several built-in methods that allow you to
D
perform operations such as adding or removing elements, sorting,
reversing, and more.
Example:
my_list = [4, 2, 1, 3]
u
my_list.append(5)
print(my_list) # Output: [4, 2, 1, 3, 5]
Ed
my_list.remove(2)
print(my_list) # Output: [4, 1, 3, 5]
my_list.sort()
print(my_list) # Output: [1, 3, 4, 5]
Tuples in python:
● A tuple is an ordered, immutable collection of elements.
● Similar to lists, tuples can store multiple items of different data
types, such as integers, floats, strings, or even other tuples.
Edu Desire 53
● However, unlike lists, tuples cannot be modified once created,
making them immutable.
e
1. Immutable:
● Once a tuple is created, its elements cannot be modified or
reassigned.
ir
● This immutability ensures the integrity of data stored in the tuple.
Example:
my_tuple = (1, 2, 3, 4, 5)
u
print(my_tuple[0]) # Output: 1
print(my_tuple[1:4]) # Output: (2, 3, 4)
Ed
Example:
# Tuple Packing
my_tuple = 1, 2, 'a'
print(my_tuple) # Output: (1, 2, 'a')
# Tuple Unpacking
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
Edu Desire 54
print(c) # Output: 'a'
5. Size and Length: You can determine the size or length of a tuple using
the len() function.
Example:
my_tuple = (1, 2, 3, 4, 5)
size = len(my_tuple)
print(size)
Output: 5
e
Remark:
● Tuples are commonly used when you want to store a collection of
values that should not be modified.
ir
● They are useful for situations where data integrity and
immutability are desired, such as representing coordinates,
database records, or returning multiple values from a function.
es
Sets in Python:
● A set is an unordered collection of unique elements.
D
● It is a built-in data structure used to store and manipulate distinct
items efficiently.
● Sets are defined using curly braces {} or the set() function.
Here's an example of creating a set in Python:
u
my_set = {1, 2, 3, 4, 5}
Ed
2. Unordered:
● Sets are unordered, meaning the elements are not stored in a
specific order.
● The order of elements in a set may change when performing
operations on the set.
Edu Desire 55
3. Mutable:
● Sets are mutable, allowing you to add or remove elements after
creation.
● You can modify the contents of a set using specific methods.
Example:
set1 = {1, 2, 3}
e
set2 = {3, 4, 5}
ir
print(union) # Output: {1, 2, 3, 4, 5}
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.remove(2)
print(my_set) # Output: {1, 3, 4}
length = len(my_set)
print(length) # Output: 3
Edu Desire 56
Remark:
● Sets are useful when you need to work with collections of unique
elements, perform mathematical set operations, or remove
duplicates from a list or sequence.
Dictionaries in python:
● A dictionary is a built-in data structure that allows you to store and
retrieve data in key-value pairs.
● It is an unordered collection of elements where each element is
identified by a unique key.
● Dictionaries are defined using curly braces {} and consist of
key-value pairs separated by colons :.
e
Here's an example of creating a dictionary in Python:
ir
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
3. Unordered:
● Dictionaries are unordered, which means the order of key-value
pairs may vary and is not guaranteed.
● The order of elements in a dictionary is based on the hash value of
the keys.
4. Accessing Values:
● You can access values in a dictionary by referencing the
corresponding key using square brackets [] or the get() method.
● If the key does not exist, an error occurs when using square
brackets, while get() returns None or a specified default value.
Example:
Edu Desire 57
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
e
my_dict['age'] = 26 # Modifying an existing key-value pair
my_dict['gender'] = 'Female' # Adding a new key-value pair
ir
print(my_dict)
es
6. Removing Entries: You can remove entries from a dictionary using the
del keyword or the pop() method, which removes and returns the value
associated with a given key.
D
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict)
Ed
Remark:
● Dictionaries are widely used when you want to store and retrieve
data using descriptive keys.
● They are useful for representing structured information,
configuration settings, or mapping relationships between entities.
● Dictionaries provide efficient lookup and retrieval operations
based on keys, making them an essential tool in Python
programming.
Edu Desire 58
● Higher-order functions allow you to treat functions as objects,
enabling powerful functional programming techniques.
Example:
numbers = [1, 2, 3, 4, 5]
def square(x):
e
return x ** 2
ir
print(list(squared_numbers))
Example:
numbers = [1, 2, 3, 4, 5]
Ed
def is_even(x):
return x % 2 == 0
Output: [2, 4]
Here, the filter() function uses the is_even() function to filter out odd
numbers from the numbers list, returning a new list of even numbers.
Edu Desire 59
3. reduce(): The reduce() function applies a given function of two
arguments cumulatively to the items of an iterable, reducing it to a single
value.
Example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
e
product = reduce(multiply, numbers)
print(product)
ir
Output: 120
4. Lambda Functions:
D
● Lambda functions (also called anonymous functions) are one-liner
functions that are defined without a name.
● They are often used in combination with higher-order functions to
provide concise function definitions.
u
Example:
numbers = [1, 2, 3, 4, 5]
Ed
Here, a lambda function is used inside the map() function to square each
element in the numbers list.
Edu Desire 60
Unit-4
File I/O & OOP
Sieve of Eratosthenes:
● The Sieve of Eratosthenes is an efficient algorithm for finding all
prime numbers up to a given limit.
● It works by iteratively marking the multiples of each prime number,
starting from 2, and eliminating the composite numbers.
e
def sieve_of_eratosthenes(limit):
primes = [True] * (limit + 1)
ir
primes[0] = primes[1] = False
p=2 es
while p * p <= limit:
if primes[p]:
for i in range(p * p, limit + 1, p):
primes[i] = False
p += 1
D
prime_numbers = []
for num in range(2, limit + 1):
if primes[num]:
u
prime_numbers.append(num)
return prime_numbers
Ed
primes = sieve_of_eratosthenes(100)
print(primes)
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97]
Edu Desire 61
Remark:
● The Sieve of Eratosthenes algorithm is highly efficient for finding
prime numbers, with a time complexity of approximately O(n log
log n), where n is the limit.
File I/O:
● A file is a container in computer storage devices used for storing
data.
● File Input/Output (I/O) operations in Python allow you to read
from and write to files on your computer.
● Python provides built-in functions and methods to perform file I/O
operations. Here's an overview of file I/O in Python:
e
1. Opening a File:
ir
● To open a file, you can use the open() function, which takes the file
path and the mode as arguments.
● The mode specifies the purpose of opening the file, such as
reading, writing, or appending.
es
Example: Opening a file for reading.
3. Writing to a File:
● To open a file for writing, use the mode 'w'. Writing to a file
replaces its existing contents.
● You can use the write() method to write data to the file.
Edu Desire 62
file.close()
4. Appending to a File:
● If you want to add content to an existing file without overwriting
it, open the file in append mode using 'a'.
● The write() method will append the data to the end of the file.
e
5. Closing a File:
● After reading from or writing to a file, it is essential to close it using
ir
the close() method.
● Closing the file ensures that all the data is written and resources are
freed.
Example:
es
file = open('example.txt', 'r')
D
content = file.read()
print(content)
file.close()
6. Error Handling:
● When working with files, it's important to handle potential errors,
such as file not found or permission issues.
● This can be done using try-except blocks to catch and handle
exceptions.
Edu Desire 63
Example:
try:
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("File not found!")
Remark:
● File I/O in Python provides a convenient way to read data from
e
files, write data to files, and manipulate file contents.
● Remember to properly handle file closures and exceptions to
ensure the integrity and reliability of your file operations.
ir
Different Modes to Open a File in Python:
Mode
es
Description
D
r Open a file for reading. (default)
Edu Desire 64
Exceptions and Assertions in python:
● Exceptions and assertions are important concepts in Python for
handling and detecting errors or exceptional conditions in your
code.
● They help in identifying and dealing with unexpected situations
that may occur during program execution.
1. Exceptions:
● Exceptions are raised when an error or exceptional condition
occurs during the execution of a program.
e
● When an exception occurs, the normal flow of program execution is
interrupted, and the program jumps to an exception handler to
ir
handle the error.
● Python provides a built-in mechanism for handling exceptions
using the try-except block.
es
Example:
try:
# Code that may raise an exception
result = 10 / 0
D
except ZeroDivisionError:
# Exception handler
print("Error: Division by zero")
Example:
try:
# Code that may raise exceptions
result = int("abc") # Raises ValueError
result = 10 / 0 # Raises ZeroDivisionError
except ValueError:
print("Error: Invalid input")
except ZeroDivisionError:
print("Error: Division by zero")
Edu Desire 65
In this example, both ValueError and ZeroDivisionError exceptions are
handled separately.
Example:
try:
# Code that may raise an exception
e
result = int("abc")
except Exception as e:
print("Error:", str(e))
ir
The Exception class is the base class for all exceptions in Python.
Catching Exception will handle any exception that occurs.
4. Assertions:
es
● Assertions are used to check if certain conditions are true during
the execution of the program.
D
● They are primarily used for debugging and to ensure that
assumptions about the program state hold true.
● If an assertion fails, it raises an AssertionError.
Example:
u
x = 10
assert x > 0, "x must be greater than 0"
Ed
Modules in python:
● Modules are files containing Python code that define functions,
classes, and variables that can be used in other Python programs.
● Modules provide a way to organize and reuse code, making it easier
to manage large programs.
Edu Desire 66
● A module is created by saving Python code in a file with a .py
extension.
● The file name becomes the module name.
● For example, a file named my_module.py creates a module named
my_module.
2. Importing Modules:
● To use the functions, classes, or variables defined in a module, you
need to import it into your program.
● Python provides different ways to import modules.
Example:
e
import my_module
ir
my_module.my_function()
my_function()
print(my_variable)
u
my_module module.
import random
Edu Desire 67
print(random_number)
e
def my_function():
print("Hello from my_module!")
ir
my_variable = 42
es
This code defines a function my_function and a variable my_variable.
Save it in a file named my_module.py to create your own module.
Remark:
D
● Modules are a fundamental concept in Python that allow you to
organize and reuse code effectively.
● They help in structuring large programs, avoiding naming conflicts,
and promoting code reusability.
● Python's standard library provides a wide range of modules to
u
accomplish common tasks, and you can create your own modules
to encapsulate and share functionality across multiple programs.
Ed
Edu Desire 68
1. Data:
● The data component specifies the type of data that the ADT can
store.
● For example, an ADT may store integers, strings, or custom objects.
2. Operations:
● The operations component defines the set of operations or
functions that can be performed on the data.
● These operations include creating, accessing, modifying, and
deleting data within the ADT.
e
● Insertion: Adding data to the ADT.
● Deletion: Removing data from the ADT.
ir
● Searching: Finding data within the ADT.
● Access: Retrieving data from the ADT.
● Update: Modifying the data within the ADT.
es
The set of operations defined for an ADT depends on the specific
requirements and behavior of the data structure.
principle. Elements can be added at the rear and removed from the front.
Ed
3. Linked List: A collection of nodes where each node contains data and
a reference to the next node.
4. Tree: A hierarchical data structure with a root node and child nodes,
commonly used for representing hierarchical relationships.
Edu Desire 69
● In Python, you can use OOP to create and work with classes and
objects.
e
2. Encapsulation:
● Encapsulation is the principle of bundling data and related
ir
methods within a class, hiding the internal implementation
details from outside access.
● Access to data is controlled through methods, providing a
level of abstraction and data protection.
3. Inheritance:
es
● Inheritance allows the creation of a new class (subclass) that
inherits attributes and methods from an existing class
D
(superclass).
● The subclass can extend or override the inherited attributes
and methods, promoting code reuse and providing a
hierarchical relationship between classes.
u
4. Polymorphism:
● Polymorphism allows objects of different classes to be
Ed
5. Method Overriding:
● Method overriding occurs when a subclass provides its own
implementation of a method inherited from the superclass.
● The method in the subclass overrides the behavior of the
same-named method in the superclass
Python Classes:
● A class is considered as a blueprint of objects.
Edu Desire 70
● We can think of the class as a sketch (prototype) of a house. It
contains all the details about the floors, doors, windows, etc. Based
on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can
create many objects from a class.
Example:
class ClassName:
e
# class definition
Here, we have created a class named ClassName.
Let's see an example,
ir
class Bike:
name = ""
gear = 0
Here,
es
● Bike - the name of the class
● name/gear - variables inside the class with default values "" and 0
D
respectively.
Python Objects:
u
objectName = ClassName()
Let's see an example,
# create class
class Bike:
name = ""
gear = 0
Edu Desire 71
Here, bike1 is the object of the class. Now, we can use this object to
access the class attributes.
e
# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"
ir
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
Output:
es
Name: Mountain Bike, Gears: 11
Example:
# define a class
class Employee:
# define an attribute
employee_id = 0
Edu Desire 72
print(f"Employee ID: {employee1.employeeID}")
Output:
Employee ID: 1001
Employee ID: 1002
e
Special Methods:
● Special methods, also known as magic methods, are predefined
ir
methods in Python classes that allow customization of object
behavior.
● They are called "special" because they are automatically invoked in
es
specific situations, such as object creation, attribute access,
comparison, and mathematical operations.
self.attr2 = arg2
2. __str__():
● The string representation method is called by the str() function or
when an object is printed.
● It returns a string representation of the object.
def __str__(self):
return f"MyClass object with attributes: {self.attr1}, {self.attr2}"
3. __len__():
● The length method is called by the len() function.
● It returns the length of the object or the number of elements it
contains.
Edu Desire 73
def __len__(self):
return len(self.data)
4. __eq__() and __ne__(): The equality and inequality methods are called
for object comparison using == and != operators, respectively.
e
5. __add__():
● The addition method is called for the + operator.
ir
● It allows objects of a class to be added together.
Python Inheritance:
D
● Like any other OOP languages, Python also supports the concept of
class inheritance.
● Inheritance allows us to create a new class from an existing class.
● The new class that is created is known as subclass (child or derived
class) and the existing class from which the child class is derived is
u
Syntax:
# define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Example:
class Animal:
Edu Desire 74
name = ""
def eat(self):
print("I can eat")
e
# create an object of the subclass
labrador = Dog()
ir
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
es
# call subclass method
labrador.display()
D
Output:
I can eat
My name is Rohu
u
labrador.name = "Rohu"
labrador.eat()
Here, we are using labrador (object of Dog) to access name and eat() of
the Animal class. This is possible because the subclass inherits all
attributes and methods of the superclass.
Also, we have accessed the name attribute inside the method of the Dog
class using self.
Edu Desire 75
is-a relationship:
● In Python, inheritance is an is-a relationship.
● That is, we use inheritance only if there exists an is-a relationship
between two classes.
Example:
● Car is a Vehicle
● Apple is a Fruit
● Cat is an Animal
Here, Car can inherit from Vehicle, Apple can inherit from Fruit, and so
on.
e
ir
es
D
u
Ed
Edu Desire 76
Unit-5
Iterators & Recursion And Sorting & Merging
Iterators:
● Iterators in Python are objects that allow iteration over a collection
of elements, such as lists, tuples, dictionaries, and more.
● They provide a way to access the elements of a collection one by
one without exposing the underlying implementation.
● Iterators are implemented using the iter() and next() functions or
by defining classes that implement the __iter__() and __next__()
methods.
e
Here's an example of using an iterator in Python:
ir
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)
es
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
Recursion:
● Recursion is a programming technique where a function calls itself
u
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Edu Desire 77
print(factorial(5))
Output: 120
e
Fibonacci series:
● Fibonacci series is a series of numbers formed by the addition of
the preceding two numbers in the series. 2.
ir
● It is simply the series of numbers which starts from 0 and 1 and
then continued by the addition of the preceding two numbers. 3.
● Example of Fibonacci series: 0, 1, 1, 2, 3, 5.
es
Here's an example of generating the Fibonacci series using a
recursive approach in Python:
D
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
u
for i in range(10):
print(fibonacci(i))
By running the above code, it will generate and print the Fibonacci series
up to the 10th number: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Edu Desire 78
Tower of Hanoi:
● Tower of Hanoi is a mathematical puzzle where we have three rods
and n disks.
● The objective of the puzzle is to move the entire stack to another
rod, obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved
if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
e
Note: Transferring the top n-1 disks from source rod to Auxiliary rod can
again be thought of as a fresh problem and can be solved in the same
manner.
ir
es
D
u
Ed
Example:
# Recursive Python function to solve the tower of hanoi
Edu Desire 79
TowerOfHanoi(n-1, auxiliary, destination, source)
# Driver code
n=4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
Output:
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Move disk 3 from source A to destination C
e
Move disk 1 from source B to destination A
Move disk 2 from source B to destination C
Move disk 1 from source A to destination C
ir
Move disk 4 from source A to destination B
Move disk 1 from source C to destination B
Move disk 2 from source C to destination A
es
Move disk 1 from source B to destination A
Move disk 3 from source C to destination B
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
D
Move disk 1 from source C to destination B
A set of instructions
Definition Function calls itself.
repeatedly executed.
Edu Desire 80
Very high(generally Relatively lower time
Time
exponential) time complexity(generally
Complexity
complexity. polynomial-logarithmic).
e
Speed recursion as it doesn’t utilize
maintaining and
the stack.
updating the stack.
ir
Recursion uses more
Iteration uses less memory as
Memory memory as compared to
compared to recursion.
iteration.
es
Linear Search:
● Linear search is a sequential searching algorithm where we start
D
from one end and check every element of the list until the desired
element is found.
● It is the simplest searching algorithm.
u
Example:
Ed
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 110;
Output : 6
Edu Desire 81
Element x is present at index 6
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].
e
Linear Search Algorithm:
LinearSearch(array, key)
ir
for each item in the array
if item == value
return its index
Example:
es
# Linear Search in Python
D
def linearSearch(array, n, x):
return i
return -1
Ed
array = [2, 4, 0, 1, 9]
x=1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)
Edu Desire 82
Binary Search:
● Binary Search is a searching algorithm for finding an element's
position in a sorted array.
● In this approach, the element is always searched in the middle of a
portion of an array.
● Binary search can be implemented only on a sorted list of items. If
the elements are not sorted already, we need to sort them first.
e
● Recursive Method
ir
The general steps for both methods are discussed below.
Low = 3 4 5 6 7 8 High = 9
u
3. Find the middle element mid of the array ie. arr[(low + high)/2] = 6.
Ed
3 4 5 Mid = 6 7 8 9
Low = 3 4 High = 5 6 7 8 9
Edu Desire 83
7. Repeat steps 3 to 6 until low meets high.
3 Mid = 4 5
8. x = 4 is found.
# Repeat until the pointers low and high meet each other
e
while low <= high:
ir
mid = low + (high - low)//2
if array[mid] == x: es
return mid
return -1
u
array = [3, 4, 5, 6, 7, 8, 9]
Ed
x=4
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
Edu Desire 84
if high >= low:
e
# Search the right half
else:
ir
return binarySearch(array, x, mid + 1, high)
else:
return -1
es
array = [3, 4, 5, 6, 7, 8, 9]
D
x=4
if result != -1:
u
print("Not found")
Sorting:
● Sorting is the process of arranging a collection of elements in a
specific order, typically in ascending or descending order.
Edu Desire 85
● Sorting allows for efficient searching, easy comparison of elements,
and improved data organization.
● There are various sorting algorithms available, each with its own
advantages and complexity characteristics.
e
Here's an example of sorting a list using the built-in sorted() function
ir
in Python:
my_list = [5, 2, 8, 1, 9, 3]
sorted_list = sorted(my_list)
print(sorted_list)
es
Output: [1, 2, 3, 5, 8, 9]
D
Merging:
● Merging refers to combining two or more sorted collections into a
single sorted collection.
● It is a fundamental operation in various algorithms, such as merge
sort and merge operation in merge sort trees.
u
Edu Desire 86
else:
merged_list.append(list2[j])
j += 1
return merged_list
# Example usage:
list1 = [1, 3, 5]
e
list2 = [2, 4, 6]
merged = merge_sorted_lists(list1, list2)
print(merged)
ir
Output: [1, 2, 3, 4, 5, 6]
es
Remark: Sorting and merging are important operations in data
processing, algorithm design, and various programming scenarios where
data organization and combination are required.
D
Selection Sort:
● Selection Sort is a simple comparison-based sorting algorithm.
● It works by repeatedly finding the minimum element from the
unsorted part of the list and swapping it with the element at the
beginning of the unsorted part.
u
Edu Desire 87
Here's an example of implementing the Selection Sort algorithm in
Python:
def selection_sort(arr):
n = len(arr)
e
# Swap the found minimum element with the first element
arr[i], arr[min_index] = arr[min_index], arr[i]
ir
return arr
# Example usage:
es
my_list = [64, 25, 12, 22, 11]
sorted_list = selection_sort(my_list)
print(sorted_list)
D
Output: [11, 12, 22, 25, 64]
individually, and then merges them to obtain the final sorted list.
Ed
Edu Desire 88
Here's an example of implementing the Merge Sort algorithm in
Python:
def merge_sort(arr):
if len(arr) <= 1:
return arr
e
# Recursively sort the two halves
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
ir
# Merge the sorted halves
return merge(left_half, right_half)
es
def merge(left, right):
merged = []
D
i=j=0
merged.append(left[i])
i += 1
Ed
else:
merged.append(right[j])
j += 1
return merged
# Example usage:
my_list = [64, 25, 12, 22, 11]
sorted_list = merge_sort(my_list)
print(sorted_list)
Edu Desire 89
Output: [11, 12, 22, 25, 64]
Remark:
● Merge Sort has a time complexity of O(n log n), making it an
efficient sorting algorithm for large datasets.
● It is a stable sorting algorithm, meaning it preserves the relative
order of equal elements.
● Merge Sort requires additional space for merging the sublists,
making it less space-efficient compared to in-place sorting
algorithms.
e
Higher Order Sort:
● A higher-order sort refers to sorting a collection based on a specific
ir
key or custom criteria defined by a function.
● This allows for more flexibility in sorting by considering elements'
properties or values beyond their default ordering.
● Two common functions used for higher-order sorting in Python are
es
sorted() and list.sort().
In this example, the key=len argument specifies that the sorting should
be based on the length of each string in the strings list.
Edu Desire 90
Example: Sorting a list of tuples based on the second element in
descending order.
e
descending order.
Remark:
ir
● Using higher-order sorting functions allows you to customize the
sorting process based on specific criteria.
● The key function provides a way to extract the relevant
es
information for sorting from each element, enabling more flexible
and precise sorting operations.
D
u
Ed
Edu Desire
Computer And Technology
Thank You!
Follow me
Edu Desire 91