0% found this document useful (0 votes)
9 views

Python-Programming-by-Edu-Desire AKTU

This document is a Python programming guide designed for B.Tech students affiliated with Dr APJ Abdul Kalam Technical University, providing a detailed syllabus and key concepts. It covers topics such as Python features, programming cycles, data types, control flow, functions, and type conversion, along with practical examples. The guide aims to assist students in quick revision and exam preparation by summarizing essential programming concepts and practices in Python.

Uploaded by

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

Python-Programming-by-Edu-Desire AKTU

This document is a Python programming guide designed for B.Tech students affiliated with Dr APJ Abdul Kalam Technical University, providing a detailed syllabus and key concepts. It covers topics such as Python features, programming cycles, data types, control flow, functions, and type conversion, along with practical examples. The guide aims to assist students in quick revision and exam preparation by summarizing essential programming concepts and practices in Python.

Uploaded by

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

Python

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

The More You Practice, The Better You Get.

Follow me

Edu Desire 1
DETAILED SYLLABUS

Unit Topic

Introduction: The Programming Cycle for Python , Python IDE,


Interacting with Python Programs , Elements of Python, Type
1 Conversion.
Basics: Expressions, Assignment Statement, Arithmetic
Operators, Operator Precedence, Boolean Expression.

Conditionals: Conditional statement in Python (if-else


statement, its working and execution), Nested-if statement and Elif
statement in Python, Expression Evaluation & Float

e
2
Representation.
Loops: Purpose and working of loops , While loop including its

ir
working, For Loop , Nested Loops , Break and Continue.

Function: Parts of A Function , Execution of A Function ,


Keyword and Default Arguments ,Scope Rules.

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.

Sieve of Eratosthenes: generate prime numbers with the help of


an algorithm given by the Greek Mathematician named
Eratosthenes, whose algorithm is known as Sieve of Eratosthenes.
u

File I/O : File input and output operations in Python


Programming.
Exceptions and Assertions
Ed

4 Modules : Introduction , Importing Modules ,


Abstract Data Types : Abstract data types and ADT interface in
Python Programming.
Classes : Class definition and other operations in the classes ,
Special Methods ( such as _init_, _str_, comparison methods and
Arithmetic methods etc.) , Class Example , Inheritance ,
Inheritance and OOP.

Iterators & Recursion: Recursive Fibonacci , Tower Of Hanoi


Search : Simple Search and Estimating Search Time , Binary
5 Search and Estimating Binary Search Time.
Sorting & Merging: Selection Sort , Merge List , Merge Sort ,
Higher Order Sort.

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.

● Python is Interactive − You can actually sit at a Python prompt


es
and interact with the interpreter directly to write your programs.

● Python is Object-Oriented − Python supports an Object-Oriented


style or technique of programming that encapsulates code within
D
objects.

● Python is a Beginner's Language − Python is a great language for


beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
u

browsers to games.
Ed

Python Features: Python's features include −

● Easy-to-learn: Python has few keywords, a simple structure, and a


clearly defined syntax. This allows the student to pick up the
language quickly.

● Easy-to-read: Python code is more clearly defined and visible to


the eyes.

● Easy-to-maintain: Python's source code is fairly easy-to-maintain.

Edu Desire 3
● A broad standard library: Python's bulk library is very portable
and cross-platform compatible with UNIX, Windows, and
Macintosh.

● Interactive Mode: Python has support for an interactive mode that


allows interactive testing and debugging of snippets of code.

● Portable: Python can run on a wide variety of hardware platforms


and has the same interface on all platforms.

● Extendable: You can add low-level modules to the Python


interpreter. These modules enable programmers to add to or

e
customize their tools to be more efficient.

ir
● Databases: Python provides interfaces to all major commercial
databases.

● GUI Programming: Python supports GUI applications that can be


es
created and ported to many system calls, libraries and Windows
systems, such as Windows MFC, Macintosh, and the X Windows
system of Unix.
D
● Scalable: Python provides a better structure and support for large
programs than shell scripting.
u

Programming Cycle for Python: Here's a simplified diagram illustrating


the basic stages of the Python programming cycle:
Ed

● Understand Problem: In this stage, you analyze and comprehend


the problem you need to solve. Understand the requirements,
constraints, and expected outcomes.

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

● Write Code: This is the implementation stage. Write the actual


code based on your plan and design. Convert your algorithmic
thinking into a Python program.

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

enhance its structure and organization.

● Deploy and Maintain: Once your code is thoroughly tested, you


Ed

can deploy it to the desired environment. This could involve


integrating it into a larger system or making it available to
end-users. Additionally, you may need to maintain the code by
applying updates, fixing issues, and addressing user feedback.

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:

● IDLE: IDLE is a simple, lightweight IDE that is included with the


Python standard library. It is a good choice for beginners who are
just starting to learn Python.

● PyCharm: PyCharm is a powerful IDE that offers a wide range of


features, including code completion, syntax highlighting, linting,
debugging, and code analysis. It is a good choice for experienced
Python developers who need a comprehensive IDE.

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

with Python programs:

● Command Line Interface (CLI):


1. You can interact with a Python program through the
command line or terminal.
2. By navigating to the directory where the Python program is
located, you can execute the program by typing python
program_name.py (assuming you have Python installed).
3. The program will run and display any output or prompts for
user input in the command line.

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

● Graphical User Interface (GUI):


1. Python provides libraries such as Tkinter, PyQt, or wxPython
that allow you to create graphical user interfaces.
2. With these libraries, you can build windows, buttons, text
boxes, and other graphical elements to provide a more

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

1. Python programs can interact with other programs or


services through Application Programming Interfaces (APIs).
2. APIs allow different applications to communicate with each
other and exchange data.
3. Python provides libraries to make HTTP requests and handle
API responses, enabling integration with external services
and systems.

Remark: These are some common ways to interact with Python


programs. Depending on your specific needs and the nature of your
program, you can choose the most suitable method to interact with and
get the desired input/output from your Python programs.

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.

● Operators: Operators perform various operations on variables and


values. Some common types of operators include:
1. Arithmetic operators: These perform mathematical
u

calculations, like addition (+), subtraction (-), multiplication


(*), division (/), etc.
Ed

2. Comparison operators: Compare values and return a


Boolean result, such as equal to (==), not equal to (!=), greater
than (>), less than (<), etc.
3. Logical operators: Combine multiple conditions and
evaluate them, such as and, or, and not.
4. Assignment operators: Assign a value to a variable, such as
=, +=, -=, *=, etc.

● Control Flow: Control flow allows you to control the execution


flow of your program. Common control flow structures include.
1. Conditional statements (if-else): Used to perform different
actions based on specific conditions.
2. Loops (for and while): Allow you to repeat a code block
multiple times.

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.

● Libraries and Modules:


1. Python provides libraries and modules that contain

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

1. Implicit Conversion - automatic type conversion


Ed

2. Explicit Conversion - manual type conversion

● Implicit type conversion is when the Python interpreter


automatically converts a variable from one data type to another.
For example, if you add an integer and a float, the Python
interpreter automatically converts the integer to a float before
performing the addition.

● Explicit type conversion is when you explicitly convert a variable


from one data type to another using a built-in function. The most
common type conversion functions in Python are
1. int(): Converts a value to an integer.
2. float(): Converts a value to a float.
3. str(): Converts a value to a string.

Edu Desire 9
4. bool(): Converts a value to a Boolean.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type

e
print("Value:",new_number)
print("Data Type:",type(new_number))

ir
Output:

Value: 124.23
es
Data Type: <class 'float'>

Example 2: Addition of string and integer Using Explicit Conversion


D
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))


u

# explicit type conversion


num_string = int(num_string)
Ed

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output:

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

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.

We have many different types of expressions in Python. Let’s discuss all


types along with some exemplar codes:
D
1. Constant Expressions: These are the expressions that have constant
values only.

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.

Here are some arithmetic operators in Python:

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

3. Integral Expressions: These are the kind of expressions that produce


only integer results after all computations and type conversions.

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.

Here are some logical operators in Python:


es
Operator Syntax Functioning
D
It returns true if both P and Q are true otherwise
and P and Q
returns false

or P or Q It returns true if at least one of P and Q is true


u

not not P It returns true if condition P is false


Ed

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

7. Bitwise Expressions: These are the kind of expressions in which


computations are performed at the bit level.

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

Note: But when we combine different types of expressions or use


multiple operators in a single expression, operator precedence comes
into play.

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:

Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

e
Unary plus or minus,

ir
3 -a , +a , ~a
complement

4 Multiply, Divide, Modulo / * // %

5
esAddition & Subtraction + –
D
6 Shift Operators >> <<

7 Bitwise AND &


u

8 Bitwise XOR ^
Ed

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

Identity and membership is, is not, in, not


13
operators in

Edu Desire 16
14 Logical Operators and, or, not

● So, if we have more than one operator in an expression, it is


evaluated as per operator precedence.
● For example, if we have the expression “10 + 3 * 4”. Going without
precedence it could have given two different outputs 22 or 52.
● But now looking at operator precedence, it must yield 22.

Let’s discuss this with the help of a Python program:

# 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

● The operator is a symbol that performs a certain operation between


two operands, according to one definition.
● In a particular programming language, operators serve as the
foundation upon which logic is constructed in a programme.

The different operators that Python offers are listed here.

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

It is used to add two operands. For example, if a =


+ (Addition)
10, b = 10 => a+b = 20

It is used to subtract the second operand from the


first operand. If the first operand is less than the
- (Subtraction)
second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15

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

It is used to multiply one operand with the other.


* (Multiplication)
es
For example, if a = 20, b = 4 => a * b = 80

It returns the remainder after dividing the first


% (reminder) operand by the second operand. For example, if a =
D
20, b = 10 => a%b = 0

As it calculates the first operand's power to the


** (Exponent)
second operand, it is an exponent operator.
u

It provides the quotient's floor value, which is


// (Floor division)
obtained by dividing the two operands.
Ed

2. Comparison operator: Comparison operators compare the values


of the two operands and return a true or false Boolean value in
accordance.

The following table lists the comparison operators:

Operator Description

If the value of two operands is equal, then the condition


==
becomes true.

Edu Desire 18
If the value of two operands is not equal, then the
!=
condition becomes true.

The condition is met if the first operand is smaller than or


<=
equal to the second.

The condition is met if the first operand is greater than or


>=
equal to the second.

If the first operand is greater than the second operand,


>
then the condition becomes true.

If the first operand is less than the second operand, then

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.

By multiplying the value of the right operand by the value


u

of the left operand, the left operand receives a changed


+=
value. For example, if a = 10, b = 20 => a+ = b will be equal
to a = a+ b and therefore, a = 30.
Ed

It decreases the value of the left operand by the value of


the right operand and assigns the modified value back to
-=
the left operand. For example, if a = 20, b = 10 => a- = b will
be equal to a = a- b and therefore, a = 10.

It multiplies the value of the left operand by the value of


the right operand and assigns the modified value back to
*=
then the left operand. For example, if a = 10, b = 20 => a* =
b will be equal to a = a* b and therefore, a = 200.

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.

a**=b will be equal to a=a**b, for example, if a = 4, b =2,


**=
a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3,


a//=b will assign 4//3 = 1 to a.

4. Bitwise Operators: The two operands' values are processed bit by

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.

If the two bits are different, the outcome bit will be


u

^ (binary xor)
1, else it will be 0.
Ed

The operand's bits are calculated as their negations,


~ (negation)
so if one bit is 0, the next bit will be 1, and vice versa.

The number of bits in the right operand is multiplied


<< (left shift)
by the leftward shift of the value of the left operand.

The left operand is moved right by the number of


>> (right shift)
bits present in the right operand.

5. Logical Operators: The assessment of expressions to make


decisions typically makes use of the logical operators.

Edu Desire 20
The following logical operators are supported by Python.

Operator Description

The condition will also be true if the expression is true. If


and the two expressions a and b are the same, then a and b
must both be true.

The condition will be true if one of the phrases is true. If a


or and b are the two expressions, then an or b must be true if
and is true and b is false.

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

If the first operand is not present in the second operand,


not in
the evaluation is true (list, tuple, or dictionary).
Ed

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

Here's a summary of the operator associativity in Python:

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.

For example, consider the expression a + b - c. Both + and - have the


es
same left-to-right associativity, so the expression is evaluated from left
to right: (a + b) - c.

On the other hand, for the exponentiation operator (**), it has


D
right-to-left associativity. So, in the expression a ** b ** c, the
exponentiation is evaluated from right to left: a ** (b ** c).

Understanding the associativity of operators is important to ensure the


intended order of operations in complex expressions and to avoid
u

unexpected results.
Ed

Edu Desire 22
Unit-2
Conditional Statements & Python Loops

Conditional statement in Python:


● In Python, conditionals allow you to control the flow of your
program based on certain conditions.
● The main conditional statements in Python are if, elif (short for
"else if"), and else.

In Python, there are three forms of the if...else statement.


1. if statement

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

2. Python if...else Statement:


● An if statement can have an optional else clause.
● The if...else statement evaluates the given condition:

e
If the condition evaluates to True
● the code inside if is executed

ir
● the code inside else is skipped

If the condition evaluates to False


● the code inside else is executed
es
● the code inside if 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

print('This statement is always executed')


Ed

Output:
Zero
This statement is always executed

4. Python Nested if statements:


● We can also use an if statement inside of an if statement. This is
known as a nested if statement.
Notes:
● We can add else and elif statements to the inner if statement as
required.
● We can also insert the inner if statement inside the outer else or elif
statements(if they exist)
● We can nest multiple layers of if statements.

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

# inner else statement


else:
es
print('Number is positive')
D
# outer else statement
else:
print('Number is negative')

Output:
u

Number is positive
Ed

Expression Evaluation in python:


● In Python, expression evaluation refers to the process of
computing the value of an expression.
● An expression is a combination of values, variables, operators, and
function calls that, when evaluated, results in a single value.
Python provides powerful capabilities for evaluating expressions.

Here are some common types of expressions and their evaluation:

1. Numeric Expressions: Numeric expressions involve mathematical


operations and are evaluated based on operator precedence and
associativity. For example:

x=5

Edu Desire 27
y=3
result = x + y * 2 # Multiplication is performed before addition
print(result)

Output: 11

2. String Expressions: String expressions involve string concatenation


or formatting. The expressions are evaluated to generate a new string. For
example:

name = "Alice"
message = "Hello, " + name + "!"

e
print(message)

Output: Hello, Alice!

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

4. Function Call Expressions: Function call expressions involve


u

invoking a function and passing arguments. The expressions are


evaluated to the return value of the function. For example:
Ed

def square(x):
return x ** 2

result = square(4) # Function call expression


print(result)

Output: 16

5. Complex Expressions: Expressions can also be more complex,


combining multiple types of expressions and using parentheses to
control evaluation order. For example:

x=5

Edu Desire 28
y=3
result = (x + y) * 2 # Expression with parentheses
print(result)

Output: 16

Remark: Python provides a rich set of operators and functions for


performing various operations on different types of expressions. By
understanding the rules of operator precedence and associativity, you
can create and evaluate complex expressions to perform computations or
generate desired results.

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)

Output: 0.30000000000000004 (not exactly 0.3)

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

Remark: If precise decimal arithmetic is required, the decimal module


can be used for higher precision decimal arithmetic.

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

1. Python for Loop: In Python, a for loop is used to iterate over


sequences such as lists, Tuples, String, etc. For example,

languages = ['Swift', 'Python', 'Go', 'JavaScript']


# run a loop for each item of the list
for language in languages:
print(language)

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

Syntax: The syntax of a for loop is:


u

for val insequence:


# statement(s)
Ed

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

Using a for Loop Without Accessing Items: It is not mandatory to use


items of a sequence within a for loop. For example:

languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')

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

until a certain condition is met.


Ed

Syntax: The syntax of while loop is:

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

# initialize the variable


i=1
D
n=5

# while loop from i = 1 to 5


while i <= n:
print(i)
u

i=i+1

Output:
Ed

1
2
3
4
5

Infinite while Loop in Python: If the condition of a loop is always True,


the loop runs for infinite times (until the memory is full). For example:

age = 32

# the test condition is always True

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

while counter < 3:


print('Inside loop')

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

Syntax: The general syntax of nested loops in Python is as follows


Ed

for outer_item in outer_sequence:


# outer loop code

for inner_item in inner_sequence:


# inner loop code

Example:

fruits = ["apple", "banana", "cherry"]


colors = ["red", "yellow", "blue"]

for fruit in fruits:


for color in colors:
print(fruit, color)

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

2. Right Triangle Star Pattern:


size = 5
for i in range(size):
for j in range(i + 1):
print("*", end=" ")
print()

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
*

4. Pyramid Star Pattern:

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

5. Diamond Star Pattern:


size = 5
for i in range(size):
for j in range(size - i - 1):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()

for i in range(size - 2, -1, -1):


for j in range(size - i - 1):
print(" ", end="")
for k in range(2 * i + 1):

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

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


Ed

target = 7

for num in numbers:


if num == target:
print("Number found!")
break
print(num)

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]

for num in numbers:


if num % 2 == 0:
es
continue
print(num)
D
print("Loop finished")

Output:
u

1
3
Ed

5
7
9
Loop finished

Edu Desire 39
Unit-3
Function & Python Data Structure

Python Functions: A function is a block of code that performs a specific


task.

Types of function: There are two types of function in Python


programming:
1. Standard library functions - These are built-in functions in
Python that are available to use.
2. User-defined functions - We can create our own functions based
on our requirements.

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.

Syntax: def function_name(arguments):.

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

under the function definition.

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

4. Return Statement (Optional):


● The return statement is used to specify the value or values that the
function should return as the result of its execution.
● It is optional, and if omitted, the function will return None by
default.

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

Python Function Declaration: The syntax to declare a function is:


u

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.

Calling a Function in Python: In the above example, we have declared a


function named greet().

def greet():
print('Hello World!')

Now, to use this function, we need to call it.


Here's how we can call the greet() function in Python.

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

Function Arguments: The following are the types of arguments that we


can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

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)

# Calling the function and passing only one argument

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

parameter names when calling a function, rather than relying on


the order of arguments in the function definition.
● By using keywords, you can explicitly associate values with
specific parameters, regardless of their position.

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)

# Calling function and passing arguments without using keyword


print( "Without using keyword" )

Edu Desire 43
function( 50, 30)

# Calling function and passing arguments using keyword


print( "With using keyword" )
function( n2 = 50, n1 = 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

Example 3: Add Two Numbers

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)

print('Sum: ', result)

Output:
u

Sum: 9
Ed

Python Variable Scope: A variable scope specifies the region where we


can access a variable.

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.

Based on the scope, we can classify Python variables into three


types:

Edu Desire 44
1. Local Variables
2. Global Variables

1. Python Local Variables:


● When we declare variables inside a function, these variables will
have a local scope (within the function).
● We cannot access them outside the function.

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

be accessed within the function.


That's why we get an error when we try to access it outside the greet()
Ed

function.
To fix this issue, we can make the variable named message global.

2. Python Global Variables:


● In Python, a variable declared outside of the function or in global
scope is known as a global variable.
● This means that a global variable can be accessed inside or outside
of the function.

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

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'

Example: Python String


# create string type variables

name = "Python"
print(name)

message = "I love Python."


print(message)

Edu Desire 46
Output:
Python
I love Python.

Access String Characters in Python: We can access the characters in a


string in three ways.

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'

# access 4th last element


print(greet[-4])
u

Output:
Ed

"e"

3. Slicing: Access a range of characters in a string by using the slicing


operator colon (:) .

Example:
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4])

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.

Python Strings are immutable: In Python, strings are immutable. That


means the characters of a string cannot be changed.

Example:
message = 'Edu Desire'
message[0] = 'E'
print(message)

Output:

e
TypeError: 'str' object does not support item assignment

However, we can assign the variable name to a new string.

ir
Example:
message = 'Edu Desire'
es
# assign new string to message variable
message = 'Hello Friends'
D
prints(message);

Output:
prints "Hello Friends"
u

Python Multiline String: We can also create a multiline string in Python.


For this, we use triple double quotes """ or triple single quotes '''.
Ed

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.

1. Compare Two Strings:


● We use the == operator to compare two strings.
● If two strings are equal, the operator returns True.
● Otherwise, it returns False.

Example:
str1 = "Hello, world!"
str2 = "I love Python."

e
str3 = "Hello, world!"

# compare str1 and str2

ir
print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
es
Output:
False
D
True

2. Join Two or More Strings: In Python, we can join (concatenate) two


or more strings using the + operator.
u

Example:
greet = "Hello, "
Ed

name = "Jack"

# using + operator
result = greet + name
print(result)

Output:
Hello, Jack

Iterate Through a Python String: We can iterate through a string using


a for loop.

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 of Python String:


Besides those mentioned above, there are various string method present
in Python. Here are some of those methods.
u

Methods Description
Ed

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

find() returns the index of first occurrence of substring

rstrip() removes trailing characters

Edu Desire 50
split() splits string from left

startswith() checks if string starts with the specified string

isnumeric() checks numeric characters

index() returns index of substring

Python String Formatting (f-Strings): Python f-Strings make it really


easy to print values and variables.

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

Here are some commonly used data structures in Python:

Python List:
Ed

● A list is a built-in data structure that allows you to store and


manipulate a collection of items.
● Lists are ordered, mutable (changeable), and can contain elements
of different data types.
● They are defined using square brackets [] and items are separated
by commas.

Here's an example of creating a list in Python:


my_list = [1, 2, 3, 'a', 'b', True]

In this example, my_list is a list that contains integers, strings, and a


boolean value.

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]

3. Slicing: Slicing allows you to extract a portion of a list. It is done by


specifying a start index, an end index (exclusive), and an optional step
size.

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4])

Edu Desire 52
Output: [2, 3, 4]

4. List Operations: Lists support various operations, including


concatenation, repetition, length calculation, membership testing, and
more.

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.

Here's an example of creating a tuple in Python:

my_tuple = (1, 2, 'a', 'b', True)

In this example, my_tuple is a tuple that contains integers, strings, and a


boolean value.

Tuples have several important characteristics:

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.

2. Ordered: Tuples maintain the order of elements as they are defined,


es
and this order is preserved throughout the tuple's lifetime.

3. Indexing and Slicing:


● You can access individual elements of a tuple using indexing,
D
similar to lists.
● Additionally, you can use slicing to extract a portion of a 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

4. Tuple Packing and Unpacking: Tuple packing involves creating a


tuple by assigning multiple values to a single variable, while tuple
unpacking involves assigning the values of a tuple to multiple variables.

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

In this example, my_set is a set that contains integers.

Sets have several important characteristics:

1. Unique Elements: Sets only contain unique elements. Duplicate values


are automatically removed, ensuring that each element appears only
once in the set.

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.

4. Mathematical Set Operations: Sets support various mathematical set


operations such as union, intersection, difference, and symmetric
difference. These operations can be performed between sets using
operators or methods.

Example:
set1 = {1, 2, 3}

e
set2 = {3, 4, 5}

union = set1 | set2

ir
print(union) # Output: {1, 2, 3, 4, 5}

intersection = set1 & set2


print(intersection)
es
# Output: {3}

difference = set1 - set2


print(difference) # Output: {1, 2}
D
symmetric_difference = set1 ^ set2
print(symmetric_difference) # Output: {1, 2, 4, 5}

5. Set Operations and Methods: Sets provide various operations and


u

methods to add or remove elements, check membership, perform set


comparisons, and more.
Ed

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

print(3 in my_set) # Output: True

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'}

In this example, my_dict is a dictionary that contains three key-value


pairs.
es
Dictionaries have several important characteristics:
D
1. Key-Value Pairs:
● Dictionaries store data as key-value pairs, where each key is unique
and associated with a corresponding value.
● Keys are used to access and retrieve values from the dictionary.
u

2. Mutable: Dictionaries are mutable, meaning you can modify, add, or


remove key-value pairs after the dictionary is created.
Ed

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'}

print(my_dict['name']) # Output: Alice


print(my_dict.get('age')) # Output: 25
print(my_dict.get('gender')) # Output: None
print(my_dict.get('gender', 'Unknown')) # Output: Unknown

5. Modifying and Adding Entries: You can modify the value of an


existing key or add new key-value pairs to a dictionary.

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'}

del my_dict['age'] # Removing a specific key-value pair


my_dict.pop('city') # Removing and returning the value of a key
u

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.

Python Higher Order Function:


● In Python, higher-order functions are functions that can take other
functions as arguments or return functions as results.

Edu Desire 58
● Higher-order functions allow you to treat functions as objects,
enabling powerful functional programming techniques.

Here are some examples of higher-order functions in Python.

1. map(): The map() function applies a given function to each item in an


iterable and returns an iterator of the results.

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

def square(x):

e
return x ** 2

squared_numbers = map(square, numbers)

ir
print(list(squared_numbers))

Output: [1, 4, 9, 16, 25]


es
In this example, the map() function applies the square() function to each
element in the numbers list, returning a new list containing the squared
values.
D
2. filter(): The filter() function applies a given function to each item in an
iterable and returns an iterator containing the items for which the
function returns True.
u

Example:
numbers = [1, 2, 3, 4, 5]
Ed

def is_even(x):
return x % 2 == 0

even_numbers = filter(is_even, numbers)


print(list(even_numbers))

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]

def multiply(x, y):


return x * y

e
product = reduce(multiply, numbers)
print(product)

ir
Output: 120

In this example, the reduce() function applies the multiply() function to


es
pairs of elements in the numbers list, resulting in the product of all the
elements.

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

squared_numbers = map(lambda x: x ** 2, numbers)


print(list(squared_numbers))

Output: [1, 4, 9, 16, 25]

Here, a lambda function is used inside the map() function to square each
element in the numbers list.

Remark: Higher-order functions and lambda functions provide powerful


tools for functional programming in Python.

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.

Here's an implementation of the Sieve of Eratosthenes algorithm in


Python:

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

In this implementation, the function sieve_of_eratosthenes takes a limit


as an argument and returns a list of prime numbers up to that limit.

Here's an example usage of the function:

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.

file = open('example.txt', 'r')


D
2. Reading from a File: Once a file is opened for reading, you can use
various methods to read its contents, such as read(), readline(), or
readlines().
u

Example: Reading the entire file content


Ed

file = open('example.txt', 'r')


content = file.read()
print(content)
file.close()

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.

Example: Writing content to a file

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


file.write('Hello, World!')

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.

Example: Appending content to a file

file = open('example.txt', 'a')


file.write('Appending more content')
file.close()

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

● It is good practice to close files explicitly.


u

● However, a more concise way to handle file operations is by using


the with statement, which automatically closes the file when the
Ed

block of code is exited.

Example: Using with statement

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


content = file.read()
print(content)

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)

Open a file for writing. Creates a new file if it does not


w
exist or truncates the file if it exists.
u

Open a file for exclusive creation. If the file already


x
exists, the operation fails.
Ed

Open a file for appending at the end of the file without


a
truncating it. Creates a new file if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)

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.

Here's an overview of exceptions and assertions in Python:

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

In this example, a ZeroDivisionError exception is raised when dividing a


u

number by zero. The try-except block catches the exception and


executes the code inside the except block, printing an error message.
Ed

2. Handling Multiple Exceptions: You can handle multiple exceptions by


specifying multiple except blocks or a single except block with multiple
exception types.

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.

3. Catching All Exceptions:


● You can use a generic except block without specifying the
exception type to catch all exceptions.
● However, it is generally recommended to handle specific
exceptions whenever possible to handle errors more precisely.

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

In this example, the assertion checks if x is greater than 0. If the


condition is False, an AssertionError is raised with the specified error
message.

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.

Here's an overview of modules in Python:


1. Creating Modules:

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

In this example, the my_module module is imported, and the function


my_function defined in the module is used.
es
3. Importing Specific Objects: You can import specific functions or
variables from a module, rather than importing the entire module.
D
Example:
from my_module import my_function, my_variable

my_function()
print(my_variable)
u

Here, only my_function and my_variable are imported from the


Ed

my_module module.

4. Standard Library Modules:


● Python comes with a rich collection of standard library modules
that provide additional functionality.
● These modules cover areas such as file I/O, math operations,
networking, date and time, and more.
● You can import and use these modules in your programs.

Example: Using the random module from the standard library

import random

random_number = random.randint(1, 10)

Edu Desire 67
print(random_number)

In this example, the random module is imported to generate a random


number.

5. Creating Your Own Modules:


● You can create your own modules by organizing related functions,
classes, and variables in a Python file.
● By using modules, you can modularize your code and make it
reusable across multiple programs.

Example: Creating a module named my_module.py

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

Abstract Data Types :


● Abstract Data Types (ADTs) are high-level data structures that
provide an abstract representation of the data and the operations
that can be performed on that data.
● They are defined by their behavior rather than their
implementation details, allowing programmers to focus on the
functionality and usage of the data structure rather than the
underlying implementation.
● ADTs serve as a blueprint for creating concrete data structures.

ADTs define the following components:

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.

Common operations include:

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.

Common examples of abstract data types include:


D
1. Stack: A data structure that follows the Last-In-First-Out (LIFO)
principle. Elements can be added or removed only from the top.

2. Queue: A data structure that follows the First-In-First-Out (FIFO)


u

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.

5. Graph: A collection of vertices (nodes) and edges that connect these


vertices, used to represent relationships between elements.

Object Oriented Programming(OOP):


● Object-Oriented Programming (OOP) is a programming paradigm
that emphasizes the organization of code around objects, which are
instances of classes.

Edu Desire 69
● In Python, you can use OOP to create and work with classes and
objects.

Here's an overview of OOP concepts in Python:

1. Classes and Objects:


● A class is a blueprint or template that defines the attributes
(data) and behaviors (methods) that objects of that class will
have.
● An object (also called an instance) is a specific instance of a
class, created using the class as a blueprint.

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

treated as objects of a common superclass.


● It enables objects to be used interchangeably, as long as they
support the same methods defined in the superclass.

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.

Define Python Class: We use the class keyword to create a class in


Python.

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.

Note: The variables inside a class are called attributes.

Python Objects:
u

● An object is called an instance of a class.


● For example, suppose Bike is a class then we can create objects like
Ed

bike1, bike2, etc from the class.

Here's the syntax to create an object:

objectName = ClassName()
Let's see an example,
# create class
class Bike:
name = ""
gear = 0

# create objects of class


bike1 = Bike()

Edu Desire 71
Here, bike1 is the object of the class. Now, we can use this object to
access the class attributes.

Example 1: Python Class and Objects


# define a class
class Bike:
name = ""
gear = 0

# create object of class


bike1 = Bike()

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

In the above example:


D
● we have defined the class named Bike with two attributes: name
and gear.
● We have also created an object bike1 of the class Bike.
● Finally, we have accessed and modified the attributes of an object
using the . notation
u

Create Multiple Objects of Python Class: We can also create multiple


Ed

objects from a single class.

Example:
# define a class
class Employee:
# define an attribute
employee_id = 0

# create two objects of the Employee class


employee1 = Employee()
employee2 = Employee()

# access attributes using employee1


employee1.employeeID = 1001

Edu Desire 72
print(f"Employee ID: {employee1.employeeID}")

# access attributes using employee2


employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")

Output:
Employee ID: 1001
Employee ID: 1002

In the above example, we have created two objects employee1 and


employee2 of the Employee class

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.

Here are some commonly used special methods in Python classes:


D
1. __init__():
● The initializer method is called when an object is created.
● It initializes the object's attributes.
u

def __init__(self, arg1, arg2):


self.attr1 = arg1
Ed

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.

def __eq__(self, other):


return self.value == other.value

def __ne__(self, other):


return self.value != other.value

e
5. __add__():
● The addition method is called for the + operator.

ir
● It allows objects of a class to be added together.

def __add__(self, other):


es
return self.value + other.value

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

known as superclass (parent or base class).


Ed

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:

# attribute and method of the parent class

Edu Desire 74
name = ""

def eat(self):
print("I can eat")

# inherit from Animal


class Dog(Animal):

# new method in subclass


def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)

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

In the above example, we have derived a subclass Dog from a superclass


Animal. Notice the statements,
Ed

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

In this example, iter() is used to create an iterator object from my_list,


D
and next() is used to retrieve the next element from the iterator.

Recursion:
● Recursion is a programming technique where a function calls itself
u

to solve a problem by breaking it down into smaller subproblems.


● It is particularly useful for solving problems that can be naturally
divided into repetitive subtasks.
Ed

● In Python, recursive functions have a base case that defines when


the recursion should stop, and a recursive case that calls the
function again with a smaller subproblem.

Here's an example of a recursive function to calculate the factorial of


a number:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

Edu Desire 77
print(factorial(5))

Output: 120

In this example, the factorial() function calculates the factorial of a


number n by recursively calling itself with a smaller subproblem until
reaching the base case (n == 0).

Remark: Recursion can be a powerful tool for solving complex problems


by breaking them down into simpler and more manageable subproblems.

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

# Generate and print the Fibonacci series up to the 10th number


Ed

for i in range(10):
print(fibonacci(i))

● In this example, the fibonacci() function takes a parameter n to


indicate the position in the Fibonacci series.
● If n is 0 or 1, it returns the corresponding value directly.
● Otherwise, it recursively calls itself with n-1 and n-2 to calculate
the Fibonacci number at position n by summing the previous two
numbers.
● The function continues to recurse until it reaches the base cases.

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

def TowerOfHanoi(n , source, destination, auxiliary):


if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)

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

Difference between recursion and iteration:


u

Property Recursion Iteration


Ed

A set of instructions
Definition Function calls itself.
repeatedly executed.

Application For functions. For loops.

Used when code size


Used when time complexity
needs to be small, and
Usage needs to be balanced against
time complexity is not
an expanded code size.
an issue.

Code Size Smaller code size Larger Code Size.

Edu Desire 80
Very high(generally Relatively lower time
Time
exponential) time complexity(generally
Complexity
complexity. polynomial-logarithmic).

Space The space complexity is


Space complexity is lower.
Complexity higher than iterations.

Here the stack is used to


store local variables
Stack Stack is not used.
when the function is
called.

Execution is slow since


Normally, it is faster than
it has the overhead of

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

Problem: Given an array arr[] of n elements, write a function to search a


given element x in arr[].

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

A simple approach is to do a linear search, i.e


● Start from the leftmost element of arr[] and one by one compare
x with each element of arr[]
● If x matches with an element, return the index.
● If x doesn’t match with any of the elements, return -1.

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

# Going through array sequencially


for i in range(0, n):
if (array[i] == x):
u

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)

Linear Search Complexities:


● Time Complexity: O(n)
● Space Complexity: O(1)

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.

Binary Search Working: Binary Search Algorithm can be implemented in


two ways which are discussed below.
● Iterative Method

e
● Recursive Method

ir
The general steps for both methods are discussed below.

The array in which searching is to be performed is:


es
3 4 5 6 7 8 9

1. Let x = 4 be the element to be searched.


D
2. Set two pointers low and high at the lowest and the highest
positions respectively.

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

4. If x == mid, then return mid.Else, compare the element to be


searched with m.
5. If x > mid, compare x with the middle element of the elements on
the right side of mid. This is done by setting low to low = mid + 1.
6. Else, compare x with the middle element of the elements on the left
side of mid. This is done by setting high to high = mid - 1.

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.

Examples (Iterative Method):


# Binary Search in python

def binarySearch(array, x, low, high):

# 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

elif array[mid] < x:


low = mid + 1
D
else:
high = mid - 1

return -1
u

array = [3, 4, 5, 6, 7, 8, 9]
Ed

x=4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

Examples (Recursive Method):


# Binary Search in python

def binarySearch(array, x, low, high):

Edu Desire 84
if high >= low:

mid = low + (high - low)//2

# If found at mid, then return it


if array[mid] == x:
return mid

# Search the left half


elif array[mid] > x:
return binarySearch(array, x, low, mid-1)

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

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
u

print("Element is present at index " + str(result))


else:
Ed

print("Not found")

Binary Search Complexity:


1. Time Complexities
● Best case complexity: O(1)
● Average case complexity: O(log n)
● Worst case complexity: O(log n)
2. Space Complexity
● The space complexity of the binary search is O(1).

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.

Some commonly used sorting algorithms include:


● Bubble Sort
● Selection Sort
● Insertion Sort
● Merge Sort
● Quick Sort
● Heap Sort

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

● Merging is commonly used in scenarios where multiple sorted lists


or arrays need to be combined into a single sorted list or when
Ed

combining sorted portions of data during divide-and-conquer


algorithms.

Here's an example of merging two sorted lists using the merge()


function in Python:

def merge_sorted_lists(list1, list2):


merged_list = []
i, j = 0, 0

while i < len(list1) and j < len(list2):


if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1

Edu Desire 86
else:
merged_list.append(list2[j])
j += 1

# Add the remaining elements from either list


merged_list.extend(list1[i:])
merged_list.extend(list2[j:])

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

● This process is repeated until the entire list is sorted.


Ed

Working of Selection Sort:


1. Set the first element as minimum.
2. Compare minimum with the second element. If the second element
is smaller than minimum, assign the second element as minimum.
3. Compare minimum with the third element. Again, if the third
element is smaller, then assign minimum to the third element
otherwise do nothing. The process goes on until the last element.
4. After each iteration, minimum is placed in the front of the unsorted
list.
5. For each iteration, indexing starts from the first unsorted element.
Step 1 to 3 are repeated until all the elements are placed at their
correct positions.

Edu Desire 87
Here's an example of implementing the Selection Sort algorithm in
Python:
def selection_sort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n - 1):
# Find the minimum element in the unsorted part
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j

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]

Merge Sort: Merge Sort is a divide-and-conquer sorting algorithm that


recursively divides the input list into smaller sublists, sorts them
u

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

# Divide the array into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

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

# Compare and merge the elements from the two halves


while i < len(left) and j < len(right):
if left[i] <= right[j]:
u

merged.append(left[i])
i += 1
Ed

else:
merged.append(right[j])
j += 1

# Add the remaining elements from either half


merged.extend(left[i:])
merged.extend(right[j:])

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

1. Using sorted() with a Key Function:


● The sorted() function can accept a key function that determines
D
the sorting criteria.
● The key function takes an element from the collection as input and
returns a value to be used for sorting.
● The sorted() function creates a new sorted list based on the key
function.
u

Example: Sorting a list of strings by their lengths in ascending order.


Ed

strings = ['cat', 'elephant', 'bird', 'dog']


sorted_strings = sorted(strings, key=len)
print(sorted_strings)

Output: ['cat', 'dog', 'bird', 'elephant']

In this example, the key=len argument specifies that the sorting should
be based on the length of each string in the strings list.

2. Using list.sort() with a Key Function:


● The list.sort() method is similar to sorted(), but it modifies the list
in-place instead of creating a new list.
● It also accepts a key function for custom sorting.

Edu Desire 90
Example: Sorting a list of tuples based on the second element in
descending order.

tuples = [(1, 4), (2, 2), (3, 7), (4, 5)]


tuples.sort(key=lambda x: x[1], reverse=True)
print(tuples)

Output: [(3, 7), (4, 5), (1, 4), (2, 2)]

In this example, the key=lambda x: x[1] argument specifies that the


sorting should be based on the second element (x[1]) of each tuple. The
reverse=True argument indicates that the sorting should be in

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

The More You Practice, The Better You Get.

Thank You!
Follow me

Edu Desire 91

You might also like