0% found this document useful (0 votes)
6 views70 pages

Python Programming Handout

The document outlines the Python Programming Course for Semester 2, detailing the modules and topics to be covered, including fundamentals of computing, algorithms, data types, conditionals, iteration, functions, and file handling. It also specifies the assessment structure, grading rubrics, and encourages student participation and collaboration. Additionally, it provides insights into algorithms, flowcharts, and the importance of iteration and functions in programming.
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)
6 views70 pages

Python Programming Handout

The document outlines the Python Programming Course for Semester 2, detailing the modules and topics to be covered, including fundamentals of computing, algorithms, data types, conditionals, iteration, functions, and file handling. It also specifies the assessment structure, grading rubrics, and encourages student participation and collaboration. Additionally, it provides insights into algorithms, flowcharts, and the importance of iteration and functions in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Sem-2

Dear Students,

Welcome to Python Programming Course! We are thrilled to have you join us on this exciting journey
into the world of Python Programming. Over the coming weeks, you will explore key concepts,
develop practical skills, and engage in hands-on projects that will enhance your understanding and
expertise.

The modules that we will cover in this course are outlined as follows:
Module Topics

Fundamentals of Computing – Identification of Computational Problems -Algorithms,


building blocks of algorithms (statements, state, control flow, functions), notation
I (pseudo code, flow chart, programming language), algorithmic problem solving,
simple strategies for developing algorithms (iteration, recursion). Illustrative
problems: find minimum in a list, Towers of Hanoi.

Python interpreter and interactive mode,debugging; values and types: int, float,
boolean, string , and list; variables, expressions, statements, tuple assignment,
II
precedence of operators, comments; Illustrative programs: exchange the values of
two variables, distance between two points.

Conditionals:Boolean values and operators, conditional (if), alternative


(if-else),chained conditional (if-elif-else);Iteration: state, while, for, break, continue,
pass; Fruitful functions: return values,parameters, local and global scope, function
III
composition, recursion; Strings: string slices,immutability, string functions and
methods, string module; Lists as arrays. Illustrative programs: gcd, exponentiation,
sum an array of numbers, linear search, binary search.

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries:
IV
operations and methods; advanced list processing - list comprehension; Illustrative
programs: simple sorting, Students marks statement, Retail bill preparation.

Files and exceptions: text files, reading and writing files, format operator; command
line arguments, errors and exceptions, handling exceptions, modules, packages;
V
Illustrative programs: word count, copy file, Voter‘s age validation, Marks range
validation (0-100).
Please note that our training process includes periodic assessments (Internal and External
Assessments)that will be crucial parts of your learning journey. We encourage you to approach these
assessments with enthusiasm and a positive mindset.
In addition, the assessment rubrics given below will be integral to your overall grading:
Category Number of Marks Pattern Syllabus
instances

Assignment 1 5 - Module 2

Mini-project 1 10 - All 5 modules

Mid semester 1 10 Number of questions: 9 Module 1, 2 and


exam theory Duration: 1.5hrs half of module 3

Mid semester lab 1 15 Number of questions: 2 Module 2 to


exam Duration: 2hrs module 5

Blended learning 1 5 Completion mode: Online Module 1,2 and 3


Duration: 8 weeks

Attendance 1 5 75% -

Semester end 1 50 Number of questions: 11 All 5 modules


exam Duration: 2hrs

Total 100 - -

We encourage you to actively participate, ask questions, and collaborate with your peers to
maximize your learning experience.

For any questions or clarifications, feel free to visit our expert trainers at Room CLC06 (Library Block -
Reading Hall) between 9:00 AM and 4:30 PM, Monday through Friday. Alternatively, you can reach
out to us via email at helpdesk@[Link].

We are thrilled to have you with us and look forward to seeing you thrive in these training sessions.
Let’s embark on this journey together, and make the most of every opportunity to grow and excel.

Happy Learning with FACE Prep!


Table of contents:

S. No Topic [Link]

1 Fundamentals of Computing
1.1 Algorithms 01
1.2 Iterations and Functions 03
Module 1: Fundamentals of Computing
Chapter 1: Algorithms and flowchart

Algorithms are a way of specifying a multi-step task, and are especially useful when we wish to
explain to a third party (be it human or machine) how to carry out steps with extreme precision.
A series of clear and efficient steps that a computer executes to solve problems, perform calculations,
process data, or make decisions to produce a result is called an algorithm.
Algorithm is a sequence of clearly defined steps that describe a process to follow a finite set of
unambiguous instructions with clear start and end points.

Properties of algorithm:
1.​Collection of individual steps: The first thing to note is that an algorithm is a series of individual
steps. This is similar to a recipe, which includes steps like "preheat the oven to 180 degrees Celsius"
or "add two tablespoons of sugar to the bowl."
2.​Definiteness: The next property is definiteness, which means every step must be clearly defined.
Each step in an algorithm should have only one meaning to avoid confusion. Similarly, chefs use
precise measurements in recipes, like "two tablespoons of sugar" or "bake for 20 minutes," instead
of vague instructions like "some sugar" or "cook it for a while."
3.​Sequential: Algorithms are also sequential, meaning the steps must be followed in the exact order
specified. Doing them out of order can lead to incorrect results. For example, in a recipe, dicing an
onion before frying it gives a different outcome than frying it first. Similarly, in math, doubling a
number and then adding 5 gives a different result than adding 5 first and then doubling it. Like a
recipe, an algorithm must be executed in the correct sequence to produce meaningful results.

State in algorithms:
The current configuration of all information kept track of by a program at any one instant in time.
As a computer follows an algorithm, much like how you follow a recipe, the state of the system can
evolve. Clearly defining the sequence of steps in an algorithm ensures that the state changes
consistently each time the algorithm is executed.
There is no "global view" in algorithms. At any given moment, the environment in which the
algorithm is running is in a specific state. However, by the time the next step is executed, things
might have changed. The recipe analogy illustrates this well. At the start, you might have butter,
flour, milk, eggs, and sugar. After each step, you take a snapshot of the kitchen, capturing how the
ingredients change bit by bit. First, the flour goes into a bowl, then the eggs join, the butter goes into
the pan, and so on.
For algorithms, this means that individual steps are executed sequentially, with only one step being
considered at any given moment. Once a step has been executed, the computer discards any
reference to it and proceeds to the next step.

Problem Statement 1: Write an algorithm for finding the minimum number in a given list of
numbers.
Solution:
Step 1: Start.
Step 2: Initialize a list of elements.

Semester 2, AIML & AIDS 1


1.1 Algorithms and flowchart

Step3: Initialize a variable ‘minimum’ with the first element possible.


Step 4: Iterate the list from the second element to the last element.
Step 4A: Compare each element in the list with the minimum variable.
Step 4B: If the current element is less than the minimum variable, update the minimum variable to
the current element.
Step 5: Print the minimum variable.
Step 6: Stop.

Flowchart Symbols:

Symbol Name Usage

Terminal/Terminator Represents the start and the


end of a flowchart.

Data/ variables Used for input and output


operation.

Process Used for arithmetic operations


and data-manipulations.

Flow Arrow Indicates the flow of logic by


connecting symbols.

Decision Used for decision making


between two or more
alternatives.

On page connector Used to join different flowline.

Off page connector Used to connect the flowchart


portion on a different page.

Semester 2, AIML & AIDS 2


Chapter 2: Iteration and Functions

Iteration:
Variables can be used to control the execution of an algorithm. At a basic level, they can be used in
two ways. One of those is iteration, also known as looping. Iteration allows you to repeat a series of
steps over and over, without the need to write out each individual step manually.
To save yourself from writing the same thing repeatedly, you could write one sentence with
instructions to repeat it.
For example: X represents the number of steps in a staircase.
At the start, X is 0.
Repeat the sentence: You are on step X of the staircase.
Take one step up. Now you are on step X+1.
Add 1 to X.
Repeat the sentence if X is less than 10, otherwise you’ve reached the top.

This is an example of iteration in action and it shows two things:


1.​How a variable is used to control the algorithm’s execution. The thing that changes with each step
is represented by a variable, in this case, the number of steps climbed. Everything else remains the
same.
2.​You need to define when the loop should stop.

This brings us to the second method used for controlling the execution of an algorithm that is
selection.

Selection:
In a loop, one way to control how many times the steps are repeated is to simply specify the number,
like ‘take 10 steps up’. But notice that the example above doesn’t do that. Instead, it uses selection
(also known as a conditional), which checks the current value of the variable and makes a decision
based on it.
In the staircase example, a condition helps decide whether to keep repeating the steps or stop. For
instance, let's say you're starting at the bottom of the staircase and need to climb up to the 10th
step. The condition might be: "Repeat taking steps as long as you haven't reached the 10th step."

At the start, you're on step 0, and the condition is true because you're not yet at step 10. So, the
computer keeps instructing you to take one step up. After each step, the number of steps remaining
decreases. Each time you take a step, the condition is checked: "Are you still on a step less than 10?"
As long as the answer is yes, the loop continues.
When you reach step 10, the condition becomes false because you've reached the top of the
staircase. Now, the computer knows that no more steps need to be taken, so it stops giving
instructions and ends the process.
In this way, the condition controls when the loop ends. As long as you're still below the 10th step,
the condition is true, and the process repeats. Once you reach the 10th step, the condition becomes
false, and the loop stops.

Semester 2, AIML & AIDS 3


1.2 Iteration and Function

Conditions can be used at any point in an algorithm, not just to control loops. Wherever they are,
they help the computer decide whether to do something or not. For example, in the staircase, the
condition could be whether you've reached the top or not, and this helps decide if you keep going or
stopping
Conditions can be used at any point in an algorithm, not just to control loops. Wherever they are,
they help the computer decide whether to do something or not. For example, in the staircase, the
condition could be whether you've reached the top or not, and this helps decide if you keep going or
stopping.

Problem statement 2: Write an algorithm and draw a flowchart to determine the number of
iterations it takes for a given number to reach 1 using the Collatz sequence.
Solution:
Step 1: Start
Step 2: Initialize an input number ‘n’ . Initialize count as ‘0’.
Step 3: Check if ‘n’ is greater than one. (or check if ‘n’ is not equal to one)
Step 3A: if true, check if ‘n’ is even. i.e., n%2==0
Step 3A1: if true, update ‘n’ as n/2
Step 3A2: if false, update ‘n’ as (3Xn)+1
Step 3A3: Increment count by 1 and go back to step 3.
Step 3B: if false, print count.
Step 4: Stop.

Semester 2, AIML & AIDS 4


1.2 Iteration and Function

Problem statement 3: Write an algorithm and draw a flowchart to determine whether the given
number is a prime number or not.
Prime number: A prime number is a natural number greater than 1 that has no positive divisors other
than 1 and itself (only 2 divisors). In other words, a prime number can only be divided by 1 and the
number itself without leaving a remainder.
Solution:
Step 1: Start.
Step 2: Initialize variables ‘count’ as zero, ‘i’ as one and an input ‘n’ from the user.
Step 3: Check if ‘i’ is less than and equal to ‘n’.
Step 4: If true, check if ‘n’ is divisible by ‘i’ (or ‘i’ divides ‘n’).
Step 4A: If true, increase count value by one.
Step 4B: Increase the value of ‘i’ by one and go back to step 3.
Step 5: If false, check if count is equal to two.
Step 5A: If true, print the output as “Prime”.
Step 5B: If false, print the output as “Not Prime”.
Step 6: Stop.

Semester 2, AIML & AIDS 5


1.2 Iteration and Function

Functions:
A subroutine is like a small, self-contained set of instructions or actions within a larger program. It's a
specific task or operation that can be used over and over without repeating the same lines of code
each time. Subroutines are also known as functions or procedures in some programming languages.

Think of a subroutine like a recipe in a cookbook. The recipe is a set of instructions for making a dish,
but it’s not followed until someone decides to cook that dish. Similarly, the lines of code inside a
subroutine aren’t executed until the programmer tells the program to "call" or "run" that subroutine.

Scenario:
Imagine you're writing a program that calculates the area of different shapes like squares, circles,
and triangles. Instead of rewriting the formula for each shape every time, you could create a
subroutine for each shape's area calculation. Each subroutine would just contain the steps to
calculate the area for that specific shape.

For example:
The Square Area Subroutine: This subroutine takes the side length of a square and returns the area
(side * side).

Semester 2, AIML & AIDS 6


1.2 Iteration and Function

The Circle Area Subroutine: This subroutine takes the radius of a circle and returns the area (π *
radius * radius).
Now, if you need to calculate the area of a square or circle in multiple parts of your program, you
don’t need to rewrite the area formula every time. Instead, you simply call the subroutine, and the
program will go to that subroutine, run the instructions, and then come back to where it left off once
the subroutine finishes.

How It Works:
Subroutine Declaration: First, the subroutine is defined with its specific set of instructions. It doesn’t
run at this point.
Subroutine Call: When the program reaches a point where it needs to calculate, for example, the
area of a square, it calls the Square Area Subroutine.
Execution: The program temporarily "jumps" to the subroutine, runs its instructions (like calculating
the area), and then returns to where it left off in the main program once the subroutine is done.

Benefits:
Reuse: You only need to write the code for a specific task once, and you can call the subroutine
anytime you need that task to be done.
Organization: It makes your code easier to organize, manage, and debug because you can break it
down into smaller, more manageable parts.
In short, a subroutine allows you to organize and reuse code efficiently, ensuring that the program
only does the work when it's needed.

Semester 2, AIML & AIDS 7


1.2 Iteration and Function

Problem statement 4: Write an algorithm and draw a flowchart to determine whether the given
number is present in an unordered list or not.
Solution without functions(without subroutines):
Step 1: Start.
Step 2: Initialize a list, variable ‘n’ for size of list, ‘i’ as zero and a variable ‘e’ that will be used for
searching within the list.
Step 3: Check if ‘i’ is less than ‘n’.
Step 4: If true, check if ‘i’th number on the list is equal to ‘e’.
Step 4A: if true, print “number is present” and go to step 6.
Step 4B: if false, Increase the variable ‘i’ by 1 and go back to step 3.
Step 5: If false, print “number is not present”.
Step 6: Stop.

Semester 2, AIML & AIDS 8


1.2 Iteration and Function

Solution with functions(with subroutines):


Step 1: Start.
Step 2: Initialize a list, variable n for the size of the list, i as 0, and a variable e that will be used for
searching within the list.
Step 3: Call the function search_number(list, n, e).
Step 4: Inside the function, check if i is less than n.
Step 5: If true, check if the ith element in the list is equal to e.
Step 5A: If true, print “number is present” and return.
Step 5B: If false, increase i by 1 and call the function again (go back to step 4).
Step 6: If i is greater than or equal to n, print “number is not present” and return.
Step 7: Stop.

Semester 2, AIML & AIDS 9


1.2 Iteration and Function

Assignment:
Similarly, consider writing an algorithm for checking whether a given number is a prime number or
not using functions (given flowchart).

Semester 2, AIML & AIDS 10


Module 2: Python Basics
Chapter 1: Introduction to Python

History:
Python was created by a programmer named Guido van Rossum and was first released on February
20, 1991. Even though "python" is also the name of a big snake, the Python programming language
actually got its name from a funny TV show called Monty Python’s Flying Circus.

One special thing about Python is that it was originally made by just one person, which is unusual.
Most programming languages are created by big companies with many experts, and we rarely know
the names of the people who worked on them. But Python is different.

Of course, Guido van Rossum didn’t build everything in Python by himself. Over time, thousands of
programmers, testers, and users (many of whom aren’t even computer experts) helped make Python
better and more popular. However, the original idea for Python came from Guido.

Today, Python is taken care of by the Python Software Foundation, a group of people who work to
improve and spread the use of Python around the world.

Key benefits of learning Python:


●​Python is easy to learn – It has simple and clear rules, so beginners can understand and start using
it quickly.
●​Python is easy to use – Writing programs in Python takes less time because its code is simple and
readable.
●​Python is free and works on different computers – You don’t have to pay to use Python, and it can
run on different operating systems like Windows, macOS, and Linux.

Python goals:
In 1999, Guido van Rossum set goals for Python. He wanted it to be:
●​ Easy to learn and use, while still being as powerful as other popular languages.
●​ Open source, so anyone could help improve it.
●​ Readable, so the code would be as easy to understand as plain English.
●​ Useful for everyday tasks, allowing programmers to write code quickly.
More than 20 years later, Python has achieved all these goals! Some rankings say it is the most
popular programming language in the world, while others place it in the top three.
Python consistently ranks at the top of the TIOBE Index and PYPL Popularity of Programming
Language Index (as of February 2022).

Semester 2, AIML & AIDS 11


2.1 Introduction to python

Areas of use:

Python is a powerful language that can be used in many areas, including:

●​ Web development – Used to create websites and web applications with frameworks like
Django, Flask, and Pyramid.
●​ Scientific and numeric computing – Helpful for math, science, and engineering with tools
like SciPy (a collection of science-related packages) and IPython (an advanced interactive
shell).
●​ Education – A great language for beginners learning to code.
●​ Desktop applications – Used to build software with tools like wxWidgets, Kivy, and Qt.
●​ Software development – Helps manage and test software using Scons, Buildbot, Apache
Gump, Roundup, and Trac.
●​ Business applications – Used in ERP (Enterprise Resource Planning) and e-commerce with
tools like Odoo and Tryton.
●​ Games – Python was used in popular games like Battlefield series and Sid Meier’s
Civilization IV.
●​ Websites and services – Major platforms like Dropbox, Uber, Pinterest, and BuzzFeed use
Python.

Google collab:
Google Colab (Colaboratory) is a free online tool that allows you to write and run Python code in a
web browser. Here’s why it’s so useful:
1.​ No Installation Needed – You don’t have to install Python or any software on your computer.
Just open Collab in your browser and start coding.
2.​ Free Access to Powerful Computers – Google Colab provides free access to GPUs and TPUs,
which are useful for machine learning and deep learning.
3.​ Cloud Storage – Your notebooks are stored in Google Drive, so you can access them from
anywhere and share them easily.
4.​ Built-in Libraries – Popular Python libraries like NumPy, Pandas, TensorFlow, and Matplotlib
are pre-installed, saving you time.
5.​ Collaboration – Multiple people can work on the same notebook in real time, just like in
Google Docs.
6.​ Supports Machine Learning and AI – It’s widely used for AI, data science, and deep learning
projects because of its easy integration with TensorFlow and PyTorch.
7.​ Free to Use – You get all these features without any cost (though there’s a paid version,
Colab Pro, with even more power).
Google Colab is an excellent choice for beginners, students, and professionals working on Python
projects.

Semester 2, AIML & AIDS 12


2.1 Introduction to python

Interpreter Vs Compiler:

Compiler Interpreter

1. Creates an object file (e.g., .exe), which is 1. No object file is needed; source code is
converted to machine code for output. directly converted to machine code.

2. Executes the entire source code at once. 2. Executes the source code line by line.

3. Faster execution. 3. Slower compared to compiled languages.

4. Debugging is harder since the whole code 4. Debugging is easier due to line-by-line
runs at once. execution.

5. Requires more memory. 5. Requires less memory.

6. Source code is not needed after the first 6. Source code is needed every time the
execution. program runs.

7. Examples: C, C++ 7. Examples: Python, JAVA

Semester 2, AIML & AIDS 13


Chapter 2: Basics

Variables:
In python, variables are named locations which are used to store data/value.
Example: a=10 or b=20 or c= “A”

Rules for variable declaration:


1.​ Variable names can only contain alphanumeric values and an underscore(_).
2.​ Variable names can not start with a digit.
3.​ Variable names in python are case-sensitive.
4.​ Python keywords can not be used as variables.
5.​ Python follows snake case convention.

Data Types:
If variables are like containers which are used to hold a value/physical entity then the data type
represents the kind of value which is stored in that container.
In python, there are majorly 5 basic data types namely, Numeric, Boolean, set, dictionary, Sequence.

Input:
There are majorly 2 types of inputs in any programming language: 1. User input.
2. File input.
For user input we can use the inbuilt function present in python: input()
Example: a = input()
Note: the default data type of input() function is string. I.e., whatever the value entered using input()
function will be in data type string only.

Semester 2, AIML & AIDS 14


2.2 Basics of Python

Type casting:
The process of converting from one kind of datatype to another kind is called type casting. We will
study more about this in upcoming chapters.
Now if we want to store the data from a user as a specific kind we need to typecast the value from
string to desired form. Refer the example given below:

Output:
For printing any output either string or variable values we use python built-in called print().
print("Hello World!")

For printing the data we use any one of the 3 formats available. But in python print() is not only
limited to printing values and texts. Further features are given below.

Semester 2, AIML & AIDS 15


2.2 Basics of Python

Different ways of printing:


1.​ Using single quotes
2.​ Using double quotes
3.​ Using 3 double quotes
4.​ Printing emoji: i. Using unicodes
ii. Using CLDR
iii. Using emoji module
5.​ Printing colored text in terminal
6.​ Formatted printing for variables

1. Using single quotes:


In python, there is very little concept of characters, so even if we use single quote or double quotes
we will be referring to sequence data type only. So either using print() by single quote or double
quote the output will be the same.
2. Using double quotes:

3. Using 3 double quotes:


This is kind of special, unlike single and double quote print statements which are limited to single line
outputs, three double quotes can be used to print output in formatted order through multiple lines.

Notice we are getting an error because as mentioned print(“”) is limited to a single line.

Semester 2, AIML & AIDS 16


2.2 Basics of Python

If we want to print in multiple lines using a single print statement we can use 3 double quotes. Or we
can also use escape sequences like ‘\n’ or ‘\t’ like these.

4. Printing Emojis:
In python we can also print emoji’s other than plain texts using print() function. For doing so we have
basic 3 approaches.
i. Using Unicodes:
ii. Using CLDR:

This is just an example, try out different emojis using the sample commands given in the below table.
Unicodes for emoji

[Link] Unicode CLDR name

1 \U0001f600 grinning face

2 \U0001f601 beaming face with smiling eyes

3 \U0001f602 face with tears of joy

4 \U0001f603 grinning face with big eyes

5 \U0001f604 grinning face with smiling eyes

6 \U0001f605 grinning face with sweat

7 \U0001f606 grinning squinting face

Semester 2, AIML & AIDS 17


2.2 Basics of Python

iii. Using the emoji module.


For emoji printing the 3rd approach is using a package called emoji. We need to first import the
package using pip command and use the builtin function emojize() with emoji name. The detailed
program is given below:

5. Printing colored text in terminal:


Not just emojis we can also colorize our text in python terminal using color codes.

Color Code

S. No Code Color

1 “\33[0m” Default

2 “\33[30m” Black

3 “\33[31m” Red

4 “\33[32m” Green

5 “\33[33m” Yellow

6 “\33[34m” Blue

7 “\33[35m” Magenta

8 “\33[36m” Cyan

9 “\33[37m” White
NOTE: Once you start printing in a specific color the interpreter will keep on printing in the chosen
one only. We need to reset to default again to avoid errors.

Semester 2, AIML & AIDS 18


2.2 Basics of Python

6. Formatted printing in python.


Printing just a text or variable data is easy in python. But how to print a combination of both of
these?
For such purpose we have methods in python:
i. Using concatenation:
For printing both variable and text we can use a comma which concatenates both type of values as a
single output.

ii. Using dot format():


This is the most widely used method for printing as we can customize spaces and position of variable
data also.

In .format if we are using multiple variable values, the order of variables inside the .format function
will appear as the same inside our curly brackets. Refer to the below example.

Semester 2, AIML & AIDS 19


2.2 Basics of Python

ii. Using f format:

Note: Programmers be aware this formatted printing method is not available in every version of
python. In competitive coding or in interviews this format may not be supportive. Use .format
extensively.

Semester 2, AIML & AIDS 20


2.2 Basics of Python

Operators:
In Python programming language, there are 7 types of operators their details are given below:

[Link] Name Operators

1 Arithmetic +​ (Addition)
-​ (Subtraction)
* (Multiplication)
/ (Division-quotient:with decimal)
% (Modulus-remainder)
// (Floor division- quotient: without decimal)
** (Exponentiation)

2 Assignment =
Shorthand operators
:= {print(x:=3)}

3 Comparison == != > < >= <=

4 Logical And or not

5 Bitwise & | ^ ~ >> <<

6 Membership in not in

7 Identity is is not

Precedence:

Semester 2, AIML & AIDS 21


Module 3: Control Statements and Data Manipulation

Chapter 1: Conditional Statements

Conditional statements in Python are used to make decisions in a program by executing specific
blocks of code based on certain conditions. They control the flow of execution, allowing the program
to respond differently in different situations.
For example, consider a traffic signal system. If the light is green, cars are allowed to move; if it's
yellow, drivers should slow down; and if it's red, vehicles must stop. Similarly, in Python, conditional
statements help a program decide what action to take based on given conditions.

There are four main types of conditional statements in python:


1.​ if statement.
2.​ If-else statement.
3.​ if-elif-else statement.
4.​ Nested if statement.
There is also a Member-case statement which acts similar to switch case in C but without the fall
through property.

1. if statement:
Syntax:

if condition:
Statement

We use the if condition when we need to execute a specific block of code only if a particular
condition is met. If the condition is True, the code inside the if block runs; otherwise, it is completely
skipped. This type of conditional statement is used when there is only one possibility—either the
condition is satisfied, and the code executes, or nothing happens.
Imagine you set an alarm to wake up in the morning. If the alarm rings, you wake up; otherwise, you
continue sleeping. There is no alternative action in this case—it’s either waking up or doing nothing.

Example:

Notice in the above two examples the print statement which is inside if-condition is being executed
only when condition evaluates to be true. The second program even when being executed without
errors doesn’t print anything because the condition part is false.

Semester 2, AIML & AIDS 22


3.1 Conditional Statements

2. If-else statement:
Syntax:
if condition:
Statement 1
else:
Statement 2

We use the if-else condition when we have exactly two possible outcomes—one if the condition is
True and another if it is False. It helps in decision-making when there are only two choices, such as
left or right, heads or tails, pass or fail.
Imagine you're flipping a coin. The result can either be heads or tails, and there are no other
possibilities.

Notice that since our condition is evaluating as false here


we are getting statement 2 as our output.

3. if-elif-else statement:
Syntax:
if condition1:
Statement 1
elif condition2:
Statement 2
elif condition3:
Statement 3
else:
Statement 4

We use the if-elif-else condition when there are multiple choices to consider, and only one condition
can be true at a time. This is useful in situations where we have more than two options, such as
choosing an engineering branch based on interest.

In the below example only the third condition is true so only the third statement will be printed. If
none of the given conditions evaluates to be true then as default statement else block will be
executed.

Semester 2, AIML & AIDS 23


3.1 Conditional Statements

4. Nested if statements:
A nested if statement is when an if condition is placed inside another if statement. This is useful
when multiple conditions must be checked in a hierarchical manner.

Consider the below example:


Imagine the Quizr platform, on the first login page, we get to observe this one where it is asking for a
college name to be entered.

Now in this stage if we enter correct college name it will enter through another page or it will throw
an error message:
Notice in the below image the website is displaying an error message as “Domain not found!”
because we are entering the college name as “Alliance” but the correct domain is “alliance”.

When we enter the proper domain it will then ask for username and password for login. Now here
only if both username and password are matching it will successfully login for the candidate. Else
error message will be displayed. (Refer to the images below and code on next page to understand
properly)

Semester 2, AIML & AIDS 24


3.1 Conditional Statements

Semester 2, AIML & AIDS 25


3.1 Conditional Statements

Code:

Now imagine the below mentioned two test cases one where domain is wrong and one where
username/password goes wrong and observe how our output statement differs.

Semester 2, AIML & AIDS 26


3.1 Conditional Statements

*Problems to understand conditionals statements:


1.​ Membership operator:
Check if a given character is a vowel or not.

In the given code we are taking an input from the user to


check and we are comparing with a list. Membership
operators are used to check whether an element is present
in a list/sequence or not. Here we are checking if user
input is in the string ‘v’ or not.

2.​ Alphabet or Not:


Check if the given character is an alphabet or not.

For a character to be an alphabet it should be


between ‘A’ to ‘Z’ which means it should be
greater than or equal to ‘A’ and also less than or
equal to ‘Z’. when both the conditions are true
only then we consider it as an alphabet. But
there is a problem with the above code. What if
the input is lowercase?

In such cases we check for both uppercase alphabet range A->Z and lowercase range a->z. Here the
character input needs to satisfy only one of the two conditions either range A->Z or range a->z not
both.

Observing these scenarios we can conclude that we use logical and operator if we need all the
conditions to be satisfied and logical or if we need any one condition to be satisfied to execute a
block of code.

Semester 2, AIML & AIDS 27


Chapter 2: Iterative statements / loops

Iteration in Python refers to the process of repeatedly executing a block of code. It is commonly used
to loop through elements in a sequence (like lists, tuples, dictionaries, or strings) or run a block of
code multiple times until a condition is met.
The process of repeatedly executing a block of code or statement with little or no modification is
called a loop. Loops are used to automate repetitive tasks and reduce manual effort.

In python there are two types of loops:


1.​ While loop.
2.​ For loop.

[Link] Loop:

Syntax:
while condition:
Statements

A while loop is used in Python to execute a block of code repeatedly as long as a given condition
remains True. It is particularly useful when the number of iterations is unknown beforehand and
depends on modification/upation of variables or dynamic conditions.
Imagine a scenario where you have 5 rupees in a savings account, and every year your money grows
5 times due to an exceptional investment opportunity. You want to track your balance until it reaches
or exceeds 100 rupees.

If we observe the above scenario, we know our initial investment, but we don't know how long it will
take to reach 100 rupees (here the number of iterations is unknown). However, we do know the end
condition, which is reaching 100 rupees. Therefore, we print the values until we reach 100, using the
condition while i < 100:
Another example for the same can be to print Collatz sequence. Starting from a number until it
reaches one.

Semester 2, AIML & AIDS 28


Write a python program to print the Collatz sequence of a given number until it reaches one. Also
calculate the number of steps it takes to reach one.

Here we already know that for odd numbers updation is: 3n+1 and for even: n//2 and we need to
keep doing this until we reach 1. Observe we know the end condition but not the number of iteration
so we use the reverse of the end condition as our loop condition. And the main task is to find the
number of steps that is the number of iterations the loop executes.

2. For loop:
A for loop in Python is used to iterate over a sequence (like a list, tuple, or range) and execute a block
of code a fixed number of times. It is particularly useful when the number of iterations is known
beforehand.

Syntax:
for i in range(start,end,step):
Statement

In the given three syntaxes, the first one is the most elaborate. Here, we have the keyword ‘for’, and
the character ‘i’ represents the iterator, which is used to check whether the value of ‘i’ falls within
the specified range of start and end values using the membership operator ‘in’. Additionally, it
includes a step value that determines the increment or decrement after each iteration.
The second syntax is not having start or step value. In such scenarios default value for start will be
considered as 0 and step value as +1.
Finally in the third syntax jump value is not given where it will be considered as +1 as before.
Note: In for loop the start value will always be inclusive and the end value specified will always be
exclusive.

Semester 2, AIML & AIDS 29


Here we can observe that even though the for loop
consists of 5 as stop value we can not see it in output
because stop value is exclusive in python loop.

Scenario:
Imagine you have 5 rupees in a savings account, and instead of growing dynamically, the bank
provides a fixed interest rate that multiplies your money by 5 each year. You want to track your
balance over a fixed period of 5 years.

Semester 2, AIML & AIDS 30


Write a python program to check whether a given number is prime or not.

If we understand this concept, we are counting the number of divisors for a given input number. We
know that the divisors of a number will always range from 1 to the number itself (n). This means that
the number of iterations required to check for divisibility is exactly ‘n’ times, which is a
predetermined (known) quantity.

Since the number of iterations is fixed and does not depend on dynamic conditions, a for loop is the
ideal choice in this scenario. The for loop allows us to systematically iterate through all numbers from
1 to n, checking whether each number is a divisor of n. If it is, we can count it as a valid divisor.

Further we have one more implementation type that is nested for loop, which we discuss in the next
chapter.

Semester 2, AIML & AIDS 31


Chapter 3: Pattern printing

Pattern printing in programming utilizes loops and control structures to generate visual
patterns—such as stars, numbers, or symbols—on the console. It serves as an effective way to
practice iteration and logic building.

Key points to remember:


1.​ For pattern printing we use nested for loop.
2.​ The outer for loop deals with row traversal.
3.​ The inner for loops deals with the number of iteration per row.

Patterns:
[Link] pattern:
n=4
J=n i j
0 4

1 4

2 4

3 4

[Link] pyramid:
J = i+1 n=4
i j
0 1

1 2

2 3

3 4

Semester 2, AIML & AIDS 32


3.3 Patterns

[Link] right pyramid:


J = n-i n=4
i j
0 4

1 3

2 2

3 1

[Link] Pyramid:

For space printing: J = n-i-1


For character printing: J = i+1 n=4

i j(Space) j(*)
0 3 1

1 2 2

2 1 3

3 0 4

Semester 2, AIML & AIDS 33


3.3 Patterns

[Link] left Pyramid:

For space printing: J = i n=4


For character printing: J = n-i
i j(Space) j(*)
0 0 4

1 1 3

2 2 2

3 3 1

[Link] triangle:

[Link] Equilateral triangle:

Semester 2, AIML & AIDS 34


3.3 Patterns

[Link] pattern:

[Link] pattern:

Semester 2, AIML & AIDS 35


3.3 Patterns

[Link] square pattern:

[Link] pattern 1:

[Link] pattern 2:

Semester 2, AIML & AIDS 36


Chapter 4: Strings

A string is a collection of characters—such as letters, numbers, symbols, and spaces—that are


enclosed within quotation marks. Essentially, it represents any text that can be typed on a keyboard.
String is a sequence type datatype in python.

You can use:


Single quotes → 'Hello'
Double quotes → "Hello"
Triple quotes → """Hello""" for multiline strings

Example:
name = "Alice"
greeting = 'Hello, world!'
sentence = "Python is fun! 123 :)"

Properties of strings:
1.​ Strings are immutable.
2.​ Strings are indexed.
3.​ Strings are iterable.
4.​ Strings can be tested using membership operators for character presence.
5.​ String supports slicing.
6.​ Strings can contain any character.

Basic operations on strings:


1. Slicing strings:
String slicing means extracting a portion (substring) from a string using a special syntax. Python lets
you slice strings using the syntax:
string[start:stop:step]
●​ start → Index where the slice begins (inclusive)
●​ stop → Index where the slice ends (exclusive)
●​ step → (Optional) How many characters to skip

text = "Python"
P y t h o n
0 1 2 3 4 5

Code: print(text[0:3])
Output: Pyt

print(text[:4]) # Output: 'Pyth'


print(text[2:]) # Output: 'thon'
print(text[:]) # Output: 'Python'
print(text[::2]) # Output: 'Pto'

Semester 2, AIML & AIDS 37


3.4 Strings

Just like lists, strings will also have negative indices starting from -1.

P y t h o n
-6 -5 -4 -3 -2 -1

print(text[-1]) # Output: 'n'


print(text[-3:-1]) # Output: 'ho'
print(text[::-1]) # Output: 'nohtyP'

Now try to find the output of the following code:


s = "Hello, Python learners"

print(s[7:12])
print(s[-6:-1])
print(s[::3])
print(s[::-2])

2. Accessing string elements:


Since string in Python is a sequence of characters. You can access each individual character in the
string using indexing.

name = "Alice"
print(name[0]) #A
print(name[-1]) #e
print(name[1]) #l
print(name[-3]) #i

You can also use loops to go through each character in a string, one by one.
Method1: using an iterator variable:
Code:
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n

Semester 2, AIML & AIDS 38


3.4 Strings

Method2: Using normal variables and length of string to iterate every index from 0 to length of
string.
Code:
text = "Python"
for i in range(len(text)):
print(f"Index {i} = {text[i]}")
Output:
(printing both index and character value)
Index 0 = P
Index 1 = y
Index 2 = t
Index 3 = h
Index 4 = o
Index 5 = n

3. Concatenation of strings.
String concatenation means joining two or more strings together to form one continuous string.
We can use the ‘+’ operator to join two different strings.
Code:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Output:
John Doe

We can also use ‘+=’ to join a string at the end of an already existing string
Code:
greeting = "Hello"
greeting += ", world!"
print(greeting)
Output:
Hello, world!

Other methods for concatenating strings:

" ".join(list) Join list of strings with separator

f"{var}" f-string (formatting)

"{}".format() Format method

Semester 2, AIML & AIDS 39


3.4 Strings

Built-in functions in Strings:


1.​ Upper case:
Converts all characters in the string to uppercase.
Code:
text = "hello world"
result = [Link]()
print(result)
Output:
HELLO WORLD

2.​ Lower case:


Converts all characters in the string to lowercase.
Code:
text = "HELLo PyThon"
result = [Link]()
print(result)
Output:
hello python

3.​ Strip leading and trailing spaces:


Removes spaces (or other characters) from the start and end of the string.
Code:
text = " David lincoln "
result = [Link]()
print(result)
Output:
David lincoln

4.​ Replace:
Replaces all occurrences of a specified substring with another.
Can be used to replace a specific indexed character or a substring.
Code:
text = "I love Java"
result = [Link]("Java", "Python")
print(result)
Output:
I love Python

5.​ Split:
Splits the string into a list of words, using a separator (default is space).
Code:
text = "apple,banana,cherry"
result = [Link](",")
print(result)

Semester 2, AIML & AIDS 40


3.4 Strings

Output:
['apple', 'banana', 'cherry']

6.​ Title:
Capitalizes the first letter of each word in the string.
Code:
text = "python is awesome"
result = [Link]()
print(result)
Output:
Python Is Awesome

Semester 2, AIML & AIDS 41


Chapter 5: Functions and recursion

A function is a block of reusable code that performs a specific task. It helps make code organized,
modular, and easier to manage.
A function is a set of instructions that executes only when it is invoked. It can accept input values,
called parameters. Functions can also produce and return a result.

Syntax for defining a function:


def function_name(parameters):
# block of code
return result

●​ def: Keyword to define a function


●​ function_name: The name of the function
●​ parameters: (Optional) inputs to the function
●​ return: (Optional) output of the function

Example:
def add_numbers(a, b):
result = a + b
return result

# Calling the function with integer values


sum_result = add_numbers(10, 5)
print("The sum is:", sum_result)

Output:
The sum is: 15

Explanation:
●​The function add_numbers takes two integer parameters: a and b.
●​It adds them and stores the result.
●​The return statement sends the result back.
●​We then print the returned value.

Parameters:
Variables a and b are parameters.
They are defined inside the function definition: def add_numbers(a, b):
Parameters are like variables that the function expects when it is called.

Arguments:
10 and 5 are arguments.
They are the actual values passed to the function in the call: add_numbers(10, 5)
These values are assigned to the parameters a and b during execution.

Semester 2, AIML & AIDS 42


3.5 Functions & recursion.

Function Types:
Type Description

Built-in functions Predefined in Python (print(), len(), etc.)

User defined functions Functions created by the user

Lambda Functions Anonymous, single-expression functions

Example 2: Sum of array elements


Code:
# Function to calculate the sum of array elements
def sum_of_array(arr):
total = 0
for num in arr:
total += num
return total

# Example array
numbers = [5, 10, 15, 20, 25]

# Calling the function


result = sum_of_array(numbers)

# Displaying the result


print("The sum of array elements is:", result)

Output:
The sum of array elements is: 75

Explanation:
●​Function name: sum_of_array
●​Parameter: arr – takes a list (array) as input.
●​Logic: Loops through each number in the array and adds it to total.
●​Return: Returns the final sum.
●​Function call: We pass numbers (the array) as an argument.

Recursion:
Recursion is a programming technique where a function calls itself to solve smaller instances of a
problem until it reaches a condition that stops the recursion (called the base case).

In Python, recursive functions are used to solve problems that can be broken down into smaller,
similar sub-problems, such as computing factorials, Fibonacci numbers, or traversing data structures
like trees.

Semester 2, AIML & AIDS 43


3.5 Functions & recursion.

Syntax or structure of recursion:


def recursive_function():
if base_condition:
return result
else:
return recursive_function(modified_argument)

Every recursive function will have 2 parts:


1.​Base Case: The stopping condition that ends the recursion.
2.​Recursive Call: The function calls itself with a smaller input.

Note:
Every recursion must have a base case to avoid infinite loops.
Python has a recursion depth limit (by default it's around 1000). You can check it with:
Too many recursive calls without a base case can result in a RecursionError.

GCD:
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)

print(gcd(24,36))

FACTORIAL:
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call

print(factorial(5)) # Output: 120

FIBONACCI:
def fibonacci(n):
"""Prints the first n Fibonacci numbers."""
If n==1 or n==2:
return n-1
else:
return fibonacci(n-1)+fibonacci(n-2)

print(fibonacci(5))

Semester 2, AIML & AIDS 44


3.5 Functions & recursion.

DECIMAL TO BINARY CONVERSION:


def bin(n):
if n==0:
return
else:
bin(n//2)
print(n%2,end="")
bin(13)

Semester 2, AIML & AIDS 45


Module 4: Lists, Tuples, Dictionaries & Sets

Chapter 1: Lists

A list is a heterogeneous, sequential data type in python which can store heterogeneous elements.
A list in Python is an ordered, mutable, and indexed collection of items. Lists can hold elements of
different data types like integers, strings, floats, or even other lists.
Example: list = [1, 2, 3, "apple", 4.5]

Properties of lists:
1.​ Lists are ordered.
2.​ Lists are mutable.
3.​ Lists can contain duplicate elements.
4.​ Lists can store elements of different data types.
5.​ Lists Dynamic in size.
6.​ Lists are iterable.

Types of lists:
1D list: A simple list where elements are stored in a single row (like a single line of data).
Ex: [ item1, item2, item3, ..., itemN ]
2D list: A list of lists — useful for representing tables, matrices, grids, etc.
Ex: [
[row1_item1, row1_item2],
[row2_item1, row2_item2],
...
]
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Accessing lists:
[Link] both string and list belong to sequence data type accessing is possible through indecis.
Ex: fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana

2. String slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50] (step by 2)

Semester 2, AIML & AIDS 46


4.1 Lists

[Link] through lists:


names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
OR
for i in range(len(names)):
print(f"Name at index {i} is {names[i]}")

[Link] list through user input:


1D lists:
# Read 5 elements from user
user_list = []
for i in range(5):
item = input(f"Enter item {i+1}: ")
user_list.append(item)
# Access an item
index = int(input("Enter index to access: "))
print("Element at index", index, "is", user_list[index])

2D lists:
matrix = [
[1, 2, 3],
[4, 5, 6]
]
print(matrix[1][2]) # Output: 6 (2nd row, 3rd column)

# Loop through 2D list


for row in matrix:
for item in row:
print(item, end=" ")

Input format:
6 #number of elements
1 3 4 9 7 5 #list elements
Code:
# Read number of elements (n)
n = int(input("Enter the number of elements: "))
# Read list elements in a single line
elements = list(map(int, input("Enter the list elements: ").split()))

# Print the list


print("List:", elements)
# Optional: print first n elements
print("First", n, "elements:", elements[:n])

Semester 2, AIML & AIDS 47


4.1 Lists

Input format:
33
123
456
789
Code:
# Read number of rows and columns
m, n = map(int, input("Enter rows and columns: ").split())
# Read 2D list (matrix) using map in a loop
matrix = []
print("Enter the matrix row by row:")
for _ in range(m):
row = list(map(int, input().split()))
[Link](row)

# Print the 2D list


print("Matrix:")
for r in matrix:
print(r)

Built-in functions in list:


1.​ append():
In Python, when you're working with a list and want to add something to the end of it, you use
the append() method. This is especially useful when you're building up a list dynamically — for
example, if you're collecting user input or results from a loop. When you call [Link](item),
the item gets placed at the very end of the list, and the list itself is changed right there in
memory. You don’t get a new list returned — the original one is just modified.

One important thing to understand is that append() only takes one item. So if you append a list,
that entire list becomes a single element inside the original list, not a merged set of values. For
instance:
nums = [1, 2]
[Link]([3, 4])
print(nums) # Output: [1, 2, [3, 4]]

2.​ remove():
The remove() function lets you delete an element from a list — not by its position, but by its
value. It searches from the beginning of the list, finds the first occurrence of the item, and
removes it. If the value appears more than once, only the first one is removed. If it doesn't exist
at all, Python will raise a ValueError, which means you’ll need to be cautious and possibly check
first if the item is in the list.
colors = ['red', 'blue', 'green', 'blue']
[Link]('blue')
print(colors) # Output: ['red', 'green', 'blue']

Semester 2, AIML & AIDS 48


4.1 Lists

NOTE: As you can see, even though "blue" appears twice, only the first one was removed. Also,
remove() doesn’t return anything; it just changes the list directly.

3.​ insert():
Sometimes, you don’t want to just stick something on the end — you want to place it at a
specific spot in the list. That’s where insert() comes in. This method takes two arguments: the
position (index) where you want the item to go, and the item itself. The element at that position
(and all following ones) will shift to the right to make space.
numbers = [10, 20, 30]
[Link](1, 15)
print(numbers) # Output: [10, 15, 20, 30]
Here, 15 gets inserted right at index 1. If the index is greater than the list’s length, the item just
gets added to the end. If the index is negative, it counts from the back of the list
4.​ pop():
This is a really useful method when you not only want to remove an item from a list but also
want to use it afterward. pop() removes an item at a specific index and returns it. If you don’t
pass any index, it just removes and returns the last item in the list. This makes it handy when
treating a list like a stack or queue.

For example:
tasks = ['code', 'test', 'deploy']
last_task = [Link]()
print(last_task) # Output: 'deploy'
print(tasks) # Output: ['code', 'test']
If you do pop(1), you’ll remove the item at index 1 instead. If the index is out of range, Python
raises an IndexError. So, like with remove(), you might need to handle that with error checking.
5.​ len():
This one isn’t a list method but a built-in function that works on all kinds of collections —
strings, tuples, dictionaries, and of course, lists. When you use len(my_list), Python returns the
number of items inside that list. This is often used in loops, conditionals, or when checking if a
list is empty.
names = ['Alice', 'Bob', 'Charlie']
print(len(names)) # Output: 3
It’s worth remembering that len() doesn’t count nested elements as individual ones — so a list
inside a list still counts as one item.

6.​ sort():
If you want to arrange the items in your list in ascending order (or descending), sort() is your
tool. It changes the original list itself — it doesn't return a new sorted version. By default, it
sorts items in ascending order, whether they're numbers or strings. If you want descending
order, you can pass reverse=True.
scores = [88, 95, 70, 100]
[Link]()
print(scores) # Output: [70, 88, 95, 100]

Semester 2, AIML & AIDS 49


4.1 Lists

marks = [45, 89, 72, 33, 90]


[Link](reverse=True)
print(marks) # Output: [90, 89, 72, 45, 33]

You can also sort based on custom rules using a key function. For example, if you have a list of
strings and want to sort them by length:
words = ['banana', 'apple', 'fig', 'cherry']
[Link](key=len)
print(words) # Output: ['fig', 'apple', 'banana', 'cherry']
Keep in mind that if you don’t want to alter the original list, but want a sorted version, you can
use the sorted() function instead.

Semester 2, AIML & AIDS 50


Chapter 2: Tuples

Definition:
In Python, a tuple is a built-in ordered collection of elements, similar to a list, but with one key
difference: tuples are immutable, meaning their contents cannot be changed once they’re created.

You can think of a tuple as a fixed-size container that stores a sequence of items — numbers, strings,
or even other tuples and lists — but once it’s created, you can't add, remove, or modify elements in
it.
You define a tuple using parentheses (), with the elements separated by commas:
my_tuple = (1, 2, 3)

Properties of tuple:
●​Ordered: Tuples maintain the order of elements. You can access elements by index.
●​Immutable: Once defined, you cannot change a tuple’s content — no adding, removing, or altering
items.
●​Allow duplicates: Just like lists, tuples can contain duplicate values.
●​Can hold mixed data types: Integers, strings, lists, other tuples — all can be elements inside a tuple.
●​Hashable (if elements are immutable): Tuples can be used as keys in dictionaries or elements in
sets, unlike lists.

Importance of tuples:
●​Data integrity: Since tuples can't be changed, they're great for data that shouldn't be modified —
like dates, coordinates, or fixed settings.
●​Performance: Tuples are slightly faster than lists for iteration and access, since their immutability
allows certain internal optimizations.
●​Safety: By using a tuple, you signal to other developers that “this data should not change.”
●​Can be dictionary keys: Because they're immutable and hashable, tuples can be used where lists
can’t — like as keys in a dictionary.
Example:
location = {(40.7128, -74.0060): "New York City"}
print(location[(40.7128, -74.0060)]) # Output: New York City

Accessing tuples:
1.​ Accessing tuples is possible just like lists, through index, using loop for individual elements or
slicing method for sequence within a tuple.

Basic operations on tuples:

1.​ Updating elements:


Once a tuple is created, its values cannot be modified. Tuples are immutable, meaning their
contents are fixed and cannot be changed after creation.
But you can convert the tuple into a list, make the necessary changes to the list, and then
convert it back into a tuple.

Semester 2, AIML & AIDS 51


4.2 Tuples

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


y = list(x)
y[1] = "kiwi"
x = tuple(y)
Once tuple is converted to list we can modify it using the same built-ins of list for
modification.

2.​ Unpacking elements:


Unpacking is a really elegant and powerful feature in Python that lets you assign the
elements of a tuple to individual variables in a single line. The number of variables on the left
must exactly match the number of elements in the tuple on the right (unless you're using the
* operator for extended unpacking).
person = ("Alice", 25, "Engineer")
name, age, profession = person

Now the variables hold:


●​name = "Alice"
●​age = 25
●​profession = "Engineer"

If you try to unpack with a different number of variables than tuple elements, Python will
raise a ValueError. But Python also supports extended unpacking, which allows you to collect
remaining values using *.
For example:
values = (1, 2, 3, 4, 5)
a, b, *rest = values
print(a) # 1
print(b) # 2
print(rest) # [3, 4, 5]
Here, the first two values are unpacked into a and b, and the remaining are collected into a
list called rest.

numbers = (10, 20, 30, 40, 50)


first, *middle, last = numbers
print(first) # 10
print(middle) # [20, 30, 40]
print(last) # 50

OR

values = (1, 2, 3, 4)
*start, end = values
print(start) # [1, 2, 3]
print(end) # 4

Semester 2, AIML & AIDS 52


4.2 Tuples

Unpacking is commonly used in scenarios like returning multiple values from a function,
iterating with enumerate() or zip(), or when destructuring values from complex structures.

3.​ Joining tuples:


Python makes it very easy to join tuples using the + operator (called the concatenation
operator). When you use + between two tuples, Python creates a new tuple that contains all
the elements from the first and second tuples, in order.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

result = tuple1 + tuple2


print(result) # Output: (1, 2, 3, 4, 5, 6)

Here, Python simply places the contents of tuple2 right after tuple1, and stores the result in
a new tuple called result.

t1 = ('a', 'b')
t2 = ('c', 'd')
t3 = ('e', 'f')

combined = t1 + t2 + t3
print(combined) # Output: ('a', 'b', 'c', 'd', 'e', 'f')

mixed1 = (1, "apple")


mixed2 = ([3, 4], (5, 6))

result = mixed1 + mixed2


print(result)
# Output: (1, 'apple', [3, 4], (5, 6))

Semester 2, AIML & AIDS 53


Chapter 3: Dictionary

In Python, a dictionary is an unordered, mutable, and indexed collection of key-value pairs. Think of it
as a real-life dictionary where you look up a word (key) and get its meaning (value). In Python, you
can store all kinds of values (strings, numbers, lists, even other dictionaries) under unique keys.

You define a dictionary using curly braces {}, with each item consisting of a key: value pair.
student = {
"name": "Alice",
"age": 21,
"course": "Computer Science"
}

Here:
●​"name" is a key with the value "Alice"
●​"age" is a key with the value 21
●​"course" is a key with the value "Computer Science"

Keys are unique and must be of an immutable type (like strings, numbers, or tuples). Values can be
anything — even lists or other dictionaries.

Properties:
●​Unordered (prior to Python 3.7), insertion ordered from Python 3.7+
●​Mutable – can change, add, or remove elements
●​Indexed using keys (not numeric positions)
●​Keys must be unique and immutable
●​Values can be of any data type
●​Dynamic in size – can grow or shrink as needed
●​Supports built-in methods like .keys(), .values(), .items(), .get(), .update(), etc.

Accessing elements:
You use the key inside square brackets [] to get its value:
student = {
"name": "Alice",
"age": 21,
"course": "Computer Science"
}

print(student["name"]) # Output: Alice


If you try to access a key that doesn’t exist, Python will raise a KeyError.

To avoid this, you can use the .get() method:


print([Link]("grade")) # Output: None
print([Link]("grade", "N/A")) # Output: N/A

Semester 2, AIML & AIDS 54


4.3 Dictionary

You can loop through keys, values, or both:


person = {"name": "Bob", "city": "London"}
# Loop through keys
for key in person:
print(key)
# Loop through keys and values
for key, value in [Link]():
print(f"{key} → {value}")
Updating values:
Dictionaries are mutable, so you can change the value associated with any key:
student = {
"name": "Alice",
"age": 21,
"course": "Computer Science"
}

student["age"] = 22
print(student) # {"name": "Alice", "age": 22, "course": "Computer Science"}

You can also add new key-value pairs just by assigning them:
student["grade"] = "A"
print(student)

Removing elements:
You can remove keys in multiple ways:

[Link] del:
del student["course"]

[Link] .pop() (also returns the value):


age = [Link]("age")

[Link] remove everything from the dictionary:


[Link]()

Nested Dictionaries:
A dictionary can contain other dictionaries. This is called nesting:
students = {
"101": {"name": "Alice", "grade": "A"},
"102": {"name": "Bob", "grade": "B"}
}
print(students["101"]["name"]) # Output: Alice

This is useful for storing complex structured data like JSON.

Semester 2, AIML & AIDS 55


Chapter 4: Sets

A set in Python is an unordered collection of unique elements.


It is used to store multiple items in a single variable, but unlike lists or tuples:
●​Duplicate values are automatically removed
●​Items are not stored in any specific order
●​Sets are useful for mathematical operations like union, intersection, and difference.
my_set = {1, 2, 3, 2, 4}
print(my_set) # Output: {1, 2, 3, 4}

Properties of sets:
●​Unordered collection (no index or position)
●​Mutable – can add or remove elements
●​No duplicate elements – each item is unique
●​Elements must be immutable (like numbers, strings, tuples)
●​Can perform set operations like union, intersection, difference
●​Created using {} or set() constructor

Accessing Elements of a Set through a Loop


In Python, sets are unordered collections of unique elements, and because they are unordered, you
cannot access their elements using indexes like you can with lists or tuples. However, you can still
access every element in a set by iterating through it using a loop. For example, if you have a set of
numbers like my_set = {10, 20, 30}, you can use a for loop to go through each element:

my_set = {1, 2, 3, 2, 4}
for item in my_set:
print(item)

This loop will print each element in the set, but the order in which the elements appear may vary
every time you run the code, because sets do not maintain order. Looping through a set is a common
way to process or display all of its items, especially when the specific order does not matter.

Adding Elements to a Set


To add elements to a set, Python provides the add() method. Since sets only store unique values, if
you try to add a value that already exists in the set, Python will simply ignore the duplicate and keep
the original value. For instance, if you have colors = {"red", "blue"} and then write
[Link]("green"), Python will add "green" to the set. But if you write [Link]("blue") again,
nothing changes because "blue" is already there. The add() method is used when you want to insert
a single element into the set.

Removing Elements from a Set


Python provides a couple of methods to remove elements from a set. The remove() method deletes
a specific element from the set, but if the element is not found, it raises a KeyError. For example, if
you have a set fruits = {"apple", "banana", "mango"} and you call [Link]("banana"), the item

Semester 2, AIML & AIDS 56


4.4 Sets

will be removed. However, if you try to remove something like [Link]("orange"), which isn’t in
the set, Python will raise an error. To avoid that, you can use the discard() method, which works
similarly but does not raise an error if the element is missing. There’s also a method called pop(),
which removes and returns an arbitrary element from the set, but since sets are unordered, you
can’t predict which element will be removed.

Updating Values in a Set


Sets do not allow direct modification of individual elements because they are unordered and do not
support indexing. So, you can’t just do something like my_set[1] = "new_value" — that will cause an
error. If you want to update a value in a set, you typically need to remove the old value and add the
new one. For example, if you want to replace "apple" with "grape" in the set fruits, you would write
[Link]("apple") and then [Link]("grape"). This simulates updating, even though you are
technically deleting and inserting a value.

Joining or Combining Sets


You can join two or more sets in Python using either the union() method or the | operator. When you
use [Link](set2), it creates a new set that contains all unique elements from both set1 and set2.
Similarly, writing set1 | set2 does the same thing. Neither of these methods modifies the original
sets unless you reassign the result. If you want to directly update one set with the contents of
another, you can use the update() method, which adds all unique elements from another set (or any
iterable) into the existing set. For example, if a = {1, 2} and b = {2, 3, 4}, then [Link](b) will make a
equal to {1, 2, 3, 4}. This is a way of combining sets in-place rather than creating a new one.

Semester 2, AIML & AIDS 57


Module 5: File handling

Chapter 1: Introduction

Need for file handling:


File handling is the process of working with files in a computer system using a programming
interface. This includes various operations such as creating a new file, opening an existing file,
reading data from it, writing data to it, and closing it after use. These operations allow programs to
store and retrieve data efficiently, making file handling an essential aspect of programming.

File handling is widely used in real-life projects across various industries and applications. It allows
programs to store, retrieve, and manipulate data efficiently.
A school or university needs to maintain student records, including names, roll numbers, grades,
attendance, and other details.
How File Handling is Used:
●​Text Files (CSV, TXT): Store student details in a structured format for easy retrieval.
●​Binary Files: Store student photos or digital signatures.
●​Reading & Writing: When a teacher updates attendance, the program reads the file, modifies the
records, and writes it back.
●​Data Backup: At the end of the academic year, all student data is backed up to a file for future
reference.

How File Handling Works


When a file is accessed, the program communicates with the operating system, which manages the
file system on the storage device (such as a hard drive, SSD, or external storage). The operating
system ensures that data is read from and written to the correct location without corruption or loss.
File handling also includes error handling mechanisms to deal with issues like missing files, incorrect
file formats, or insufficient permissions.

Advantages of File Handling


●​Data Storage and Retrieval – Files allow programs to store data permanently instead of relying on
temporary memory (RAM), which is lost when the program stops running.
●​Data Organization – Files help structure and manage data systematically, making it easy to retrieve
specific information when needed.
●​Large Data Management – Unlike variables, which store limited data in memory, files can store vast
amounts of data without affecting program performance.
●​Data Sharing – Files can be shared between different programs and users, making them useful for
communication and collaboration.
●​Security and Backup – Files can be protected using encryption and access controls, and they can also
be backed up to prevent data loss.

Disadvantages of File Handling


●​Slower Access Speed – Reading and writing files from storage is slower compared to accessing data in
memory (RAM).

Semester 2, AIML & AIDS 58


5.1 Introduction to file handling

●​Complexity – Managing files, especially large ones, requires careful handling of file paths, formats,
and permissions.
●​Risk of Data Corruption – If files are not properly closed or if there is a system crash, data may be lost
or corrupted.
●​Storage Space – Large files consume significant disk space, which can become an issue if storage is
limited.
●​Security Vulnerabilities – Files can be accessed by unauthorized users if not properly protected,
leading to potential data breaches.

Types of files for python file handling:


Python provides powerful file handling capabilities to work with different file types, including:
1.​ Text Files (Plain text, CSV, JSON, XML)
2.​ Binary Files (Images, Audio, Video, Executable files)
3.​ Log Files (For system monitoring)
4.​ Configuration Files (INI, ENV)
5.​ Pickle Files (For object serialization)

1. Text Files (.txt, .csv, .json, .xml, etc.)


Text files store data in human-readable format and contain characters encoded in ASCII or Unicode.
These files can be opened and edited using any text editor.

Types of Text Files


(a) Plain Text Files (.txt)
●​ Contains simple unformatted text.
●​ Used for storing logs, configuration settings, and notes.

(b) Comma-Separated Values (.csv)


●​ Stores tabular data where values are separated by commas.
●​ Used in databases, spreadsheets, and data analysis.

(c) JSON Files (.json)


●​ Stores structured data in JavaScript Object Notation (JSON) format.
●​ Commonly used for API responses and data exchange.

(d) XML Files (.xml)


●​ Stores data in a structured format using tags.
●​ Used in web services, configuration files, and data exchange.

2. Binary Files (.bin, .dat, .jpg, .png, .mp4, etc.)


Binary files store data in a format that is not human-readable. They are mainly used for multimedia,
images, executable files, and custom data formats.

Semester 2, AIML & AIDS 59


5.1 Introduction to file handling

Types of Binary Files


(a) General Binary Files (.bin, .dat)
●​ Stores data in raw binary format.
●​ Used for storing encoded or compressed information.

(b) Image Files (.jpg, .png, .gif)


●​ Used to store pictures and graphics.
●​ Python’s PIL (Pillow) library can handle image files.

(c) Audio and Video Files (.mp3, .wav, .mp4)


●​ Stores music, sounds, and video content.
●​ Python libraries like pydub (for audio) and moviepy (for video) are used to manipulate these
files.

(d) PDF Files (.pdf)


●​ Used for storing formatted documents.
●​ Python’s PyPDF2 or pdfplumber library can read and write PDFs.

3. Log Files (.log)


●​ Stores system logs, error messages, and event records.
●​ Used in server logs, debugging, and monitoring.

4. Configuration Files (.ini, .cfg, .env)


●​ Stores settings and configurations for applications.
●​ Used in software programs and web development.

5. Pickle Files (.pkl)


●​ Used to store Python objects (lists, dictionaries, etc.) in a serialized format.
●​ Useful for machine learning models and caching.

Semester 2, AIML & AIDS 60


Chapter 2: Basic operations and modes.

The basic file operations in Python include:


1.​ Creating (x mode)
2.​ Opening (open())
3.​ Writing (w, a modes)
4.​ Reading (r mode)
5.​ Closing (close())
6.​ Deleting ([Link]())
7.​ File exist

Mode Usage

‘x’ Creates a new file for writing. Fails if the file exists.

‘r’ Opens an existing file for reading. Fails if the file does not exist.

‘w’ Opens a file for writing. Creates a new file if it does not exist, or truncates an existing
file.

‘a’ Opens a file for appending. Creates a new file if it does not exist.

‘r+’ Opens a file for both reading and writing. Fails if the file does not exist.

‘w+’ Opens a file for both reading and writing. Creates a new file if it does not exist, or
truncates an existing file.

‘a+’ Opens a file for both reading and appending. Creates a new file if it does not exist.

1.​ ‘x’ Mode:


In Python, the 'x' mode is used when you want to create a new file but want to ensure that
the file does not already exist. This mode stands for "exclusive creation." When you open a
file using 'x', Python will create a new file for writing.

# Trying to create a new file using 'x' mode


file = open("sample_file.txt", "x")
[Link]("This file was created without using exception handling.")
[Link]()

However, if a file with the same name already exists, it will raise a FileExistsError and stop
the program. This behavior makes 'x' mode especially useful when you want to avoid
accidentally overwriting an existing file.

Semester 2, AIML & AIDS 61


5.2 Basic operations and modes

For example, if you write open('[Link]', 'x') and there is no file named [Link] in
the current directory, Python will create it. You can then write data to the file as usual using
write(). But if you try the same line again and the file [Link] already exists, Python will
not open it and instead throw an error.

This mode is helpful in scenarios where the integrity of existing data is critical, and you want
to make sure you're creating something entirely new without affecting what’s already there.
Unlike 'w' mode which can overwrite existing files, 'x' mode prioritizes safety by avoiding
overwriting files.

2.​ ‘w’ Mode:


In Python, the 'w' mode stands for "write" and is used to create a new file or open an
existing file for writing. When a file is opened in 'w' mode, Python will either create a new
file if it doesn't already exist or, if the file does exist, it will completely erase (truncate) the
file's contents before writing to it.

This means that using 'w' mode is destructive to existing content — anything that was in the
file before will be lost. Therefore, it should be used with caution when working with existing
files.

file = open("[Link]", "w")


[Link]("This text will overwrite any existing content.")
[Link]()
In this example, if a file named [Link] already exists, its content will be erased, and the
new text will be written. If it doesn't exist, Python will create it and then write the text.

3.​ ‘r’ Mode:


In Python, the 'r' mode is used to open a file for reading only. This is the default mode if no
mode is specified when opening a file. When a file is opened in 'r' mode, Python expects the
file to already exist. If the file does not exist, Python will raise a FileNotFoundError, and the
program will stop.

This mode allows you to read the content of the file, but you cannot modify or write to the
file while it is open in 'r' mode. It is typically used when you just want to view or process data
stored in an existing file.

file = open("[Link]", "r")


content = [Link]()
print(content)
[Link]()
In this example, the program opens the file [Link] for reading. If the file exists, its
contents are read and printed. If the file doesn't exist, Python will throw an error.

Semester 2, AIML & AIDS 62


5.2 Basic operations and modes

4.​ ‘a’ Mode:


In Python, the 'a' mode stands for "append", and it is used to open a file for writing, but
without erasing the existing content. If the file already exists, Python will open it and place
the write cursor at the end of the file, allowing you to add new data after the existing
content. If the file does not exist, Python will create a new one.

This makes 'a' mode especially useful when you want to add information to a file without
deleting or overwriting what's already in it. Unlike 'w' mode, 'a' mode ensures that the
original data remains intact.

file = open("[Link]", "a")


[Link]("New entry added.\n")
[Link]()
In this example, if the file [Link] exists, the line "New entry added." will be added to the end
of the file. If the file doesn’t exist, Python will create it and write the line.

5.​ ‘w+’ Mode:


In Python, the 'w+' mode opens a file for both reading and writing. It is a combination of 'w'
(write) and 'r' (read) modes. When a file is opened in 'w+' mode, Python first clears the
contents of the file (if it exists) or creates a new file if it doesn’t exist. This means any existing
data is immediately erased when the file is opened.

After opening the file, you can perform both read and write operations. However, one
important point is that the file pointer is positioned at the beginning, and reading
immediately after writing (or vice versa) requires repositioning the file pointer using seek().

file = open("[Link]", "w+")


[Link]("Hello Python!")
[Link](0) # Move pointer back to the beginning before reading
content = [Link]()
print(content) # Output: Hello Python!
[Link]()
In this case, we first write data to the file, then use seek(0) to move the cursor back to the
start, so we can read what we just wrote. Without calling seek(0), read() would return an
empty string because the cursor would still be at the end of the file.

file = open("[Link]", "w+")


print([Link]()) # Output: (empty string, because file was just created and is empty)
[Link]("New content added.")
[Link](0)
print([Link]()) # Output: New content added.
[Link]()
In this case, since 'w+' clears the file contents upon opening, the first read() gives nothing.
We then write new content and use seek(0) again to read it back.

Semester 2, AIML & AIDS 63


5.2 Basic operations and modes

6.​ ‘r+’ Mode:


In Python, 'r+' mode opens a file for both reading and writing, just like 'w+'. However, unlike
'w+', it does not truncate the file or create a new one if it doesn’t exist. Instead, 'r+' requires
that the file must already exist, or Python will raise a FileNotFoundError. This mode is useful
when you want to modify the content of an existing file without deleting it.

After opening the file in 'r+' mode, the file pointer starts at the beginning, meaning you can
read from or overwrite existing content right away. However, similar to 'w+', switching
between reading and writing (or vice versa) requires using seek() to reposition the file
pointer.

file = open("[Link]", "r+")


original = [Link]()
print("Before writing:", original)
[Link](0) # Go back to the beginning to overwrite
[Link]("New")
[Link](0)
print("After writing:", [Link]())
[Link]()
In this example, the program reads the original content of the file, then writes "New" at the
beginning (overwriting part of the original content), and finally reads the modified file again.
Since the file pointer moves during operations, seek() is used to reset it before reading again.

file = open("[Link]", "r+")


[Link]("Hello") # Overwrites the first few characters
[Link](0)
print("After writing:", [Link]())
[Link]()
Here, we start by writing "Hello" into the existing file. Since writing starts from the beginning
and doesn’t erase the full file, it overwrites only the first few characters, and the rest of the
file remains. After seeking back to the start, we read the updated content.

7.​ ‘a+’ Mode:


In Python, the 'a+' mode opens a file for both appending and reading. This means you can
read the content of the file and also write new data to the end of it. If the file does not exist,
Python will create it automatically. Unlike 'r+' or 'w+', this mode never erases existing
content — it always writes at the end of the file, no matter where the file pointer is.

When you open a file in 'a+' mode, the file pointer is initially placed at the end, so if you
want to read the contents, you’ll need to manually move the pointer to the beginning using
seek(0).

Semester 2, AIML & AIDS 64


5.2 Basic operations and modes

file = open("[Link]", "a+")


[Link](0) # Move to the beginning to read the content
print("Before appending:\n", [Link]())

[Link]("New entry added.\n")


[Link]()
Here, we first use seek(0) to read the existing content. Then, we write a new line. This line is
always added at the end, regardless of the current pointer position.

file = open("[Link]", "a+")


[Link]("Another log entry.\n") # Always added at the end
[Link](0)
print("After appending:\n", [Link]()) # Will include all previous and new content
[Link]()
In this example, even if we haven't moved the file pointer after writing, the write operation
appends to the end. To see everything, including what was just added, we must use seek(0)
before reading.

Semester 2, AIML & AIDS 65


Chapter 3: Modules

In Python, a module is simply a file containing Python code — it can include functions, classes,
variables, and even runnable code. Modules help you organize your code by breaking it into smaller,
reusable parts. Instead of writing all code in one file, you can keep related code in a separate file
(module) and use it when needed.

Python comes with many built-in modules (like math, random, os) that you can use to perform
various tasks. You can also create your own custom modules.

Types of Modules:
●​Built-in Modules – Already available in Python (e.g., math, datetime, os)
●​User-defined Modules – Python files you create to reuse code (e.g., my_utils.py)
●​External Modules – Installed using tools like pip (e.g., numpy, pandas)

1.​Every .py file is a module.


2.​Python uses the import statement to access module contents.
3.​You can view available functions in a module using dir().

Now imagine we have created a module named [Link] as follows:

# [Link]
def fibonacci(n):
"""Prints the first n Fibonacci numbers."""
If n==1 or n==2:
return n-1
else:
return fibonacci(n-1)+fibonacci(n-2)

def factorial(n):
"""Returns the factorial of n."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

Let us discuss how to call modules individually.


Method 1: Import the Entire Module
# [Link]
import mymath # importing the whole module
[Link](6) # Output: 5
print([Link](5)) # Output: 120

You access functions using module_name.function_name().

Semester 2, AIML & AIDS 66


5.3 Modules

Method 2: Import specific functions


# [Link]
from mymath import fibonacci, factorial # importing specific functions
fibonacci(6) # Output: 5
print(factorial(5)) # Output: 120

Now you can use the functions directly without the module prefix.

Semester 2, AIML & AIDS 67

You might also like