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

Python Solution

This document provides information about a laboratory manual for a Python Programming course. It includes details like the course code, term, and institute. It outlines the visions and missions of the Directorate of Technical Education and the institute. The document also includes a preface describing the aims of the manual and a mapping of practical outcomes to course outcomes. It lists 22 experiments along with the relevant course outcomes for each. The experiments cover topics like algorithms, Python basics, control structures, functions, strings and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
440 views

Python Solution

This document provides information about a laboratory manual for a Python Programming course. It includes details like the course code, term, and institute. It outlines the visions and missions of the Directorate of Technical Education and the institute. The document also includes a preface describing the aims of the manual and a mapping of practical outcomes to course outcomes. It lists 22 experiments along with the relevant course outcomes for each. The experiments cover topics like algorithms, Python basics, control structures, functions, strings and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

Diploma

Engineering

Laboratory Manual
Python Programming

(4311601)

[Information Technology / First Semester]


Enrolment No

Name

Branch

Academic Term

Institute

Directorate Of Technical Education


Gandhinagar - Gujarat
PythonProgramming(4311601)

DTE’s Vision:
● To provide globally competitive technical education;
● Remove geographical imbalances and inconsistencies;
● Develop student friendly resources with a special focus on girls’ education
and support to weaker sections;
● Develop programs relevant to industry and create a vibrant pool of technical
professionals.

DTE’s Mission:

Institute’s Vision:

Institute’s Mission:

Department’s Vision:

Department’s Mission:
PythonProgramming(4311601)

Certificate

This is to certify that Mr./Ms ………………………………………………………………….


Enrollment No. ………….……………. of …….………. Semester of Diploma in of
………………………………………………………………………. (GTU Code) has satisfactorily completed the
term work in course for the academic year:
…………………… Term: Odd/Even prescribed in the GTU curriculum.

Place:…………………..

Date: …………………..

Signature of Course Faculty Head of the Department


PythonProgramming(4311601)

Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as well
as creative ability amongst students to solve real time problems by developing relevant competencies in
psychomotor domain. Keeping in view, GTU has designed competency focused outcome-based
curriculum -2021 (COGC-2021) for Diploma engineering programmes. In this more time is allotted to
practical work than theory. It shows importance of enhancement of skills amongst students and it pays
attention to utilize every second of time allotted for practical amongst Students, Instructors and Lecturers
to achieve relevant outcomes by performing rather than writing practice in study type. It is essential for
effective implementation of competency focused outcome- based Green curriculum-2021. Every
practical has been keenly designed to serve as a tool to develop & enhance relevant industry needed
competency in each and every student. These psychomotor skills are very difficult to develop through
traditional chalk and board content delivery method in the classroom. Accordingly, this lab manual has
been designed to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.

By using this lab manual, students can read procedure one day in advance to actual performance
day of practical experiment which generates interest and also, they can have idea of judgement of
magnitude prior to performance. This in turn enhances predetermined outcomes amongst students. Each
and every Experiment /Practical in this manual begins by competency, industry relevant skills, course
outcomes as well as practical outcomes which serve as a key role for doing the practical. The students
will also have a clear idea of safety and necessary precautions to be taken while performing experiment.
This manual also provides guidelines to lecturers to facilitate student-centered lab activities for
each practical/experiment by arranging and managing necessary resources in order that the students
follow the procedures with required safety and necessary precautions to achieve outcomes. It also gives
an idea that how students will be assessed by providing Rubrics.
Python is a popular language for solving a wide range of problems, and experimenting with
Python programming can help students develop problem-solving skills that are valuable in many
industries. By working on coding challenges and projects, students can learn how to break down complex
problems into smaller, more manageable pieces, and develop logical, efficient solutions using Python
code.By experimenting with Python programming, students can develop a strong foundation in these
concepts, which can be applied to other programming languages and tools.

Although we try our level best to design this lab manual, but always there are chances of
improvement. We welcome any suggestions for improvement.

3 | Page
PythonProgramming(4311601)

Programme Outcomes (POs) :

1. Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the engineering
problems.

2. Problem analysis: Identify and analyse well-defined engineering problems using codified
standard methods.

3. Design/ development of solutions: Design solutions for engineering well-defined technical


problems and assist with the design of systems components or processes to meet specified
needs.

4. Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.

5. Engineering practices for society, sustainability and environment: Apply appropriate


technology in context of society, sustainability, environment and ethical practices.

6. Project Management: Use engineering management principles individually, as a team


member or a leader to manage projects and effectively communicate about well-defined
engineering activities.

7. Life-long learning: Ability to analyze individual needs and engage in updating in the context
of technological changes in field of engineering.

4 | Page
PythonProgramming(4311601)

Practical Outcome - Course Outcome matrix


Course Outcomes (COs):
CO1 Prepare flowchart and algorithm for solving computing problems.
CO2 Develop python programs to solve simple problems
CO3 Apply control structure feature of python for developing programs.
CO4 Develop a program in Python using built-in functions, modules, and library functions
CO5 Develop python programs applying strings and lists manipulation concepts.
CO1 CO2 CO3 CO4 CO5
S. No. Practical Outcome/Title of experiment

Prepare flowchart and algorithm for a given


problem.(Following are the sample programs.
Faculty can select any other similar programs for the
practice of the students.)
1. i. Find the sum of two given numbers. ✓
ii. Find a maximum out of two given numbers. iii.
Find whether a given number is odd or even. iv.
Find a maximum out of three given numbers.
2. Install & configure python software. ✓

Create a program to print your name, mobile ✓


3. number, and date of birth
Develop a program to identify data-types in python. ✓
4.

Create a program to read three numbers from the ✓


5. user and find the average of the numbers.
Develop a program that can calculate simple interest ✓
6. and compound interest on given data.
Write a program to convert temperature from ✓
7.
Fahrenheit to Celsius unit using eq: C=(F-32)/1.8
Identify whether the scanned number is even or odd ✓
8.
and print an appropriate message
Create a program to find a maximum number among ✓
9. the given three numbers.
Develop a program to demonstrate the basic ✓
10.
functionalities of a standard calculator.
Write a python program to print 1 to 10 numbers ✓
11.
using loops.
Develop a program to find odd and even numbers ✓
12. from 1 to N numbers. (Where N is an integer
number)
Write a program to show whether the entered ✓
13. number is prime or not.

5 | Page
PythonProgramming(4311601)

Create a program to display the following patterns. ✓

A) B)
1 *****
12 ****
14.
123 ***
1234 **
12345 *

Create a user-defined function to print the ✓


15. Fibonacci series of 0 to N numbers. (Where N is an
integer number and passed as an argument)
Develop a user-defined function to find the factorial ✓
16. of a given number.
Write a program using the function that reverses ✓
17. the entered value.
Write a program that determines whether a given ✓
18. number is an armstrong number or a palindrome
using a user-defined function.
Write a program to find the length of a string. ✓
19.

Write a program to reverse words in a given ✓


20. sentence.
Write a program to check if a substring is present in ✓
21. a given string
Write a program to count and display the number of ✓
22. vowels, consonants, uppercase, lowercase
characters in a string.
Develop programs to perform the following list ✓
operations.
23. a) To swap given two elements in a list.
b) To find the sum of elements in a list.
Develop programs to perform the following list ✓
operations.
24. a) To check if an element exists in a given list.
b) To find the smallest and largest element in a given
list.
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, ✓
36, 49, 64, 81, 100]. Write one line of Python that
takes this list and makes a new list that has only the
even elements of this list in it.
25. b) Create a list containing the square of all odd
numbers from range 1 to 10.
c) Create a list of prime and non-prime numbers in
range 1 to 50.

6 | Page
PythonProgramming(4311601)

Industry Relevant Skills

The following industry relevant skills are expected to be developed in the students by
performance of experiments of this course.

● Problem-solving skills
● Programming fundamentals
● Collaboration skills

Guidelines to Course Faculty


1. Course faculty should demonstrate experiment with all necessary implementation
strategies described in curriculum.
2. Course faculty should explain industrial relevance before starting of each experiment.
3. Course faculty should involve & give opportunity to all students for hands on experience.
4. Course faculty should ensure mentioned skills are developed in the students by asking.
5. Utilise 2 hrs of lab hours effectively and ensure completion of write up with quiz also.
6. Encourage peer to peer learning by doing same experiment through fast learners.

Instructions for Students

1. Organize the work in the group and make record of all observations.
2. Students shall develop maintenance skill as expected by industries.
3. Student shall attempt to develop related hand-on skills and build confidence.
4. Student shall develop the habits of evolving more ideas, innovations, skills etc.
5. Student shall refer technical magazines and data books.
6. Student should develop habit to submit the practical on date and time.
7. Student should well prepare while submitting write-up of exercise.

7 | Page
PythonProgramming(4311601)

Continuous Assessment Sheet


Enrolment No: Name
Name: Term:

Sr no Practical Outcome/Title of experiment Page Date Marks Sign


(25)
1 Prepare flowchart and algorithm for a given
problem.(Following are the sample programs. Faculty
can select any other similar programs for the practice
of the students.)
i. Find the sum of two given numbers.
ii. Find a maximum out of two given numbers. iii. Find
whether a given number is odd or even. iv. Find a
maximum out of three given numbers.
2 Install & configure python software.
Create a program to print your name, mobile number,
3 and date of birth
4 Develop a program to identify data-types in python.

5 Create a program to read three numbers from the user


and find the average of the numbers.

6 Develop a program that can calculate simple interest


and compound interest on given data.
7 Write a program to convert temperature from
Fahrenheit to Celsius unit using eq: C=(F-32)/1.8
8 Identify whether the scanned number is even or odd
and print an appropriate message

9
Create a program to find a maximum number among
the given three numbers.
10 Develop a program to demonstrate the basic
functionalities of a standard calculator.
11 Write a python program to print 1 to 10 numbers using
loops.
12 Develop a program to find odd and even numbers from
1 to N numbers. (Where N is an integer number)
13 Write a program to show whether the entered number
is prime or not.
PythonProgramming(4311601)

14
Create a program to display the following patterns.

A) B)
1 *****
12 ****
123 ***
1234 **
12345 *

15
Create a user-defined function to print the Fibonacci
series of 0 to N numbers. (Where N is an integer
number and passed as an argument)
16
Develop a user-defined function to find the factorial of
a given number.

17
Write a program using the function that reverses the
entered value.

18
Write a program that determines whether a given
number is an armstrong number or a palindrome using
a user-defined function.
19 Write a program to find the length of a string.
20 Write a program to reverse words in a given sentence.

21
Write a program to check if a substring is present in a
given string

22
Write a program to count and display the number of
vowels, consonants, uppercase, lowercase characters
in a string.
23
Develop programs to perform the following list
operations.
a) To swap given two elements in a list.
b) To find the sum of elements in a list.
24
Develop programs to perform the following list
operations.
a) To check if an element exists in a given list.
b) To find the smallest and largest element in a given
list.
25
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes
this list and makes a new list that has only the even
elements of this list in it.
b) Create a list containing the square of all odd
numbers from range 1 to 10.
c) Create a list of prime and non-prime numbers in
range 1 to 50.
PythonProgramming(4311601)

Date: ……………
Practical No.1:Prepare flowchart and algorithm for a given problem.(Following are the sample
programs. Faculty can select any other similar programs for the practice of the students.)
i. Find the sum of two given numbers.
ii. Find a maximum out of two given numbers.
iii. Find whether a given number is odd or even.
iv. Find a maximum out of three given numbers.

A. Objective:

After performing this experiment students will be able to:


● Prepare flowchart for a given problem
● Prepare algorithm for a given problem

B. Expected Program Outcomes (POs)


PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


Basic knowledge of flowchart and algorithm

D. Expected Course Outcomes(Cos)


CO1
E. Practical Outcome(PRo)

Able to use symbols for a flowchart and prepare an algorithm for a given problem.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
An algorithm is a set of steps or instructions that a computer program follows in
order to solve a problem or perform a specific task. Algorithms are usually written
in a structured way using a specific syntax or language, and they are used to describe
how a program should behave.
A flowchart is a graphical representation of an algorithm that uses various shapes
and symbols to represent different types of instructions or steps. Flowcharts help
to visualize the logical sequence of steps involved in a process or algorithm, making
it easier to understand and analyze. They are used to design, document, and
communicate complex algorithms or procedures in a clear and concise way.
PythonProgramming(4311601)

Q.1Prepareflowchartandalgorithmtofindthesumoftwogiven numbers.Flowchart:

Algorithm:

Step1:Start
Step 2: Declare variables num1, num2 and
sum.Step3:Readvaluesfornum1,num2.
Step 4: Add num1 and num2 and assign the result to
avariablesum.
Step 5: Display
sumStep6:Stop

H. Program Logic-Flow chart :


PythonProgramming(4311601)

Symbols for Flow chart:

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X
PythonProgramming(4311601)

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Prepare flowchart and algorithms for remaining programs:

Q.2 Prepare flowchart and algorithm to find a maximum out of two


givennumbers.

Flowchart:

Algorithm:
PythonProgramming(4311601)

Q.3Prepareflowchartandalgorithmtofindagivennumberisoddoreven.Flowchart:

Algorithm:
PythonProgramming(4311601)

Q.4 Prepare flowchart and algorithm to find a maximum out of three


givennumbers.
Flowchart:

Algorithm:

L. Practical related Quiz.


PythonProgramming(4311601)

• Prepare flowchart and algorithm to read a number N and print all its divisors.
• Draw a flowchart to find the sum of given N numbers.

M. References / Suggestions
1. https://www.programiz.com/article/flowchart-programming
2. https://infomaxacademy.com/concept-of-python-exchanging-values-of-
two-variables
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………

Practical No.2: Install & configure python software.

A. Objective:

After performing this experiment students will be able to:

Install and configure python.


B. Expected Program Outcomes (POs)
PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to learn the configuration and installation skill of software.

D. Expected Course Outcomes(Cos)


CO2
E. Practical Outcome(PRo)

Ability to use python programming.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:

How to install Python on Windows?

Since windows don’t come with Python preinstalled, it needs to be installed


explicitly. Here we will define step by step tutorial on How to install Python on
Windows. Follow the steps below:
Download Python Latest Version from python.org
Step 1: First and foremost step is to open a browser and
type https://www.python.org/downloads/windows/
Step 2: Underneath the Python Releases for Windows find the LatestPython 3
Release – Python 3.11.2 (the latest stable release as of now is Python 3.11.2).
PythonProgramming(4311601)

Step 3: On this page move to Files and click on Windows x86-64 executable installer for
64-bit or Windows x86 executable installer for 32-bit.

Here we are providing the installation process of Python 3.11.2 on Windows


⮚ Run the Python Installer for how to install python on windows downloads folder
⮚ Make sure to mark Add Python 3.11 to PATH otherwise you will have to do it
explicitly. It will start installing python on windows.
PythonProgramming(4311601)

⮚ After installation is complete click on Close.Python is installed. Now go to windows


and type IDLE.

● This is Python Interpreter also called Python Shell. I printed Hello geeks, python is
working smoothly.
● The three greater than >>> sign is called Python command prompt, where we write our
program and with a single enter key, it will give result so instantly.
H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
PythonProgramming(4311601)

1 Computer system OS: Windows 7 or higher Ver., 01


macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X
I. Safety and necessary Precautions followed

Use the most recent version of Python


Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. References / Suggestions
1. https://www.geeksforgeeks.org/download-and-install-python-3-latest-
version/
2. https://realpython.com/installing-python/

K. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: ……………

Practical No.3: Create a program to print your name, mobile number, and date of birth.

A. Objective:
To create a program that prints your name, mobile number, and date of birth as
output.
B. Expected Program Outcomes (POs)
PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● By working on this program, students will reinforce their knowledge of these core
concepts.
D. Expected Course Outcomes(Cos)

CO2
E. Practical Outcome(PRo)

Able to apply ‘print’ function.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Prerequisites:
Basic understanding of programming concepts (variables, data types, functions,
control structures)
Familiarity with Python syntax and basic string manipulation
Step1:WritingtheProgram
A. OpenatexteditororanIntegratedDevelopmentEnvironment(IDE)ofyour choice(e.g.,
VisualStudioCode,PyCharm).
B. Createanewfileandsaveitwitha‘.py’extension,suchas‘personal_info.py’.

Step2:DefiningtheProgram Logic
1.Startbydefiningafunctionthatwillhandletheprintingofpersonalinformation.Addthefollo
wing codetoyour‘personal_info.py’file:
defprint_personal_info(name,mobile_number,date_of_birth):
PythonProgramming(4311601)

print("Name:", name)
print("Mobile Number:", mobile_number)
print("Date of Birth:", date_of_birth)

2. This function takes three parameters: ‘name’, ‘mobile_number’, and


‘date_of_birth’. It uses the ‘print’ function to display the information with
appropriate labels.
3. Save the file after adding the code.

Step 3: Gathering Input and Calling the Function


1. Add the following code to your ‘personal_info.py’ file to gather input from
the user and call the ‘print_personal_info’ function: python

name = input("Enter your name: ")


mobile_number = input("Enter your mobile number: ")
date_of_birth = input("Enter your date of birth: ")

print_personal_info(name,mobile_number,date_of_birth)

2. This code prompts the user to enter their name, mobile number, and date
of birth using the ‘input’ function. The entered values are stored in the
respective variables (‘name’, ‘mobile_number’, ‘date_of_birth’).
3. Finally, the ‘print_personal_info’ function is called with the gathered input
to display the information.

Step 4: Running the Program


1. Open a terminal or command prompt.
2. Navigate to the directory where you saved the ‘personal_info.py’ file.
3. Run the program by executing the following command:

pythonpersonal_info.py

4. The program will prompt you to enter your name, mobile number, and date
of birth. After providing the input, it will print the information on the
console.
PythonProgramming(4311601)

H. Experimental set up/ Program Logic-Flow chart :


Refer Practical – 1

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Practical related Quiz.
1: Create a program to greet the morning to your friend using ‘print’ function.

Source Code:# Greet your friend in the morning

def greet_morning():

print("Good morning, my friend!")

# Call the function to greet your friend

greet_morning()
PythonProgramming(4311601)

Output:

L. References / Suggestions
https://docs.python.org/3/tutorial/
M. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.04: Develop a program to identify data-types in python.

A. Objective:
Use of data-types in python programming to build the any program.

B. Expected Program Outcomes (POs)


PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply data-types to solve real world problems in python programming.

D. Expected Course Outcomes(Cos)


CO2
E. Practical Outcome(PRo)
Development of a program using data-types.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
• The ‘identify_data_type()’ function takes a value as input and checks its type
using the ‘isinstance()’ function.
• The program uses a series of ‘if’ and ‘elif’ statements to determine the type
of the value. It checks for various common data types such as ‘int’, ‘float’,
‘str’, ‘bool’, ‘list’,’ tuple’, and ‘dict’, along with ‘None’.
• If the type of the value matches any of the conditions, the corresponding
data type is returned as a string.
• If the value does not match any of the known data types, the program
returns "Unknown".
• The user is prompted to enter a value using the’input()’ function, and the
program stores it in the ‘user_input’ variable.
• The program then calls the ‘identify_data_type()’ function with ‘user_input’
as the argument to determine the data type.
PythonProgramming(4311601)

• Finally, the program prints the data type of the entered value using an f-
string.

H. Program Logic &source code:


Source Code:

def identify_data_type(value):
if isinstance(value, int):
return "Integer"
elifisinstance(value, float):
return "Float"
elifisinstance(value, str):
return "String"
elifisinstance(value, bool):
return "Boolean"
elifisinstance(value, list):
return "List"
elifisinstance(value, tuple):
return "Tuple"
elifisinstance(value, dict):
return "Dictionary"
elif value is None:
return "None"
else:
return "Unknown"

# User input
user_input = input("Enter a value: ")

# Identify and print the data type data_type


= identify_data_type(user_input)
print(f"The data type of {user_input} is {data_type}")

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X
PythonProgramming(4311601)

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Practical related Quiz.
1: Write a python program to calculate the sum of two numbers.

Source code:

# Input two numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Calculate the sum

sum = num1 + num2

# Display the result

print("The sum of", num1, "and", num2, "is", sum)

Output:
PythonProgramming(4311601)

L. References / Suggestions
1. https://www.tutorialspoint.com/python/python_data_types.htm

2. https://www.programiz.com/python-programming

M. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.5: Create a program to read three numbers from the user and find the
average of the numbers.

A. Objective:

Make a use of input output operations in python.

B. Expected Program Outcomes (POs)


PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Ability to use input output operations in python.

D. Expected Course Outcomes(Cos)


CO2
E. Practical Outcome(PRo)
Develop a program to find the average of the numbers.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory and program code:
# Read three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Calculate the average


average = (num1 + num2 + num3) / 3

# Print the average


print("The average of the three numbers is:", average)

Explanation:
PythonProgramming(4311601)

1. The program prompts the user to enter three numbers using the input() function.
We use the float() function to convert the input to a floating-point number,
allowing decimal values.
2. The three numbers are stored in the variables num1, num2, and num3, respectively.
3. To calculate the average, we add the three numbers together and divide the sum by
3. The result is stored in the variable average.
4. Finally, the program prints the calculated average using the print() function. We
concatenate the average value with the string "The average of the three numbers
is:" using a comma (,) to separate them in the print statement.

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Practical related Quiz.
1: Implement the python program to calculate total and average marks based on
input from user.

Source Code:

# Get the number of subjects from the user


num_subjects = int(input("Enter the number of subjects: "))

# Initialize variables to store total and average marks


total_marks = 0
PythonProgramming(4311601)

# Input marks for each subject and calculate the total


for i in range(num_subjects):
subject_marks = float(input(f"Enter marks for subject {i+1}: "))
total_marks += subject_marks

# Calculate the average


average_marks = total_marks / num_subjects

# Display the total and average marks


print(f"Total Marks: {total_marks}")
print(f"Average Marks: {average_mar
PythonProgramming(4311601)

Output:

K. References / Suggestions
1. https://www.tutorialspoint.com/python/python_numbers.htm
2. https://www.programiz.com/python-programming
3. https://www.w3schools.com/python/
4. https://www.geeksforgeeks.org/python-programming-language/
L. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.06: Develop a program that can calculate simple interest and compound interest
on given data.

A. Objective:

Make a use of operators in Python

B. Expected Program Outcomes (POs)


PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Able to use operators in python.

D. Expected Course Outcomes(Cos)


CO2
E. Practical Outcome(PRo)
To calculate simple interest and compound interest for given data.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Program code and theory:
def calculate_simple_interest(principal, rate, time):
# Simple Interest formula: SI = (P * R * T) / 100
interest = (principal * rate * time) / 100
return interest

def calculate_compound_interest(principal, rate, time):


# Compound Interest formula: CI = P * (1 + R/100) ** T - P
interest = principal * (pow((1 + rate / 100), time)) - principal
return interest
PythonProgramming(4311601)

# Get user inputs


principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the interest rate: "))
time = float(input("Enter the time period (in years): "))

# Calculate Simple Interest


simple_interest = calculate_simple_interest(principal, rate, time)
print("Simple Interest:", simple_interest)

# Calculate Compound Interest


compound_interest = calculate_compound_interest(principal, rate, time)
print ("Compound Interest:", compound_interest)
Explanation:
1. The program defines two functions: calculate_simple_interest and
calculate_compound_interest. Each function takes three parameters: principal (the
initial amount), rate (the interest rate), and time (the time period in years).
2. The calculate_simple_interest function uses the simple interest formula (P * R * T)
/ 100 to calculate the interest amount and returns it.
3. The calculate_compound_interest function uses the compound interest formula P
* (1 + R/100) ** T - P to calculate the interest amount and returns it.
4. The program prompts the user to enter the principal amount, interest rate, and time
period.
5. It calls the calculate_simple_interest function with the provided inputs and assigns
the result to the simple_interest variable.
6. It calls the calculate_compound_interest function with the provided inputs and
assigns the result to the compound_interest variable.
7. Finally, it prints the calculated simple interest and compound interest.
PythonProgramming(4311601)

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Practical related Quiz.
1: Write a program which accepts the radius of a circle from the user and
compute the area.

Source Code

radius = float(input("Enter the radius of the circle:"))


area = 3.14159 * (radius ** 2)
print("The area of the circle is:", area)
PythonProgramming(4311601)

Output:

K. References / Suggestions
1. https://www.tutorialspoint.com/python/python_numbers.htm
2. https://www.programiz.com/python-programming
3. https://www.w3schools.com/python/
4. https://www.geeksforgeeks.org/python-programming-language/

L. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.07: Write a program to convert temperature from Fahrenheit to Celsius unit using
equation: C=(F-32)/1.8

A. Objective:
Make a use of Arithmetic expressions in python.
B. Expected Program Outcomes (POs)
PO1, PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


Able to use arithmetic expressions in python programming.
D. Expected Course Outcomes(Cos)

CO2
E. Practical Outcome(PRo)
Calculate conversion from Fahrenheit to Celsius.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Program Code and Theory:
def convert_fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) / 1.8
return celsius

# Get user input for temperature in Fahrenheit


fahrenheit = float(input("Enter temperature in Fahrenheit: "))

# Convert Fahrenheit to Celsius


celsius = convert_fahrenheit_to_celsius(fahrenheit)

# Print the result


PythonProgramming(4311601)

print("Temperature in Celsius:", celsius)


Explanation:

1. The program defines a function called convert_fahrenheit_to_celsius that takes the


temperature in Fahrenheit as an input parameter.
2. Inside the function, the temperature is converted from Fahrenheit to Celsius using
the formula (F - 32) / 1.8.
3. The calculated Celsius value is returned from the function.
4. The program prompts the user to enter the temperature in Fahrenheit.

5. The input temperature is stored in the variable fahrenheit.


6. The program calls the convert_fahrenheit_to_celsius function, passing the
fahrenheit value as an argument, and assigns the returned Celsius value to the
variable celsius.
7. Finally, it prints the converted temperature in Celsius.

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
PythonProgramming(4311601)

J. Practical related Quiz.


1: Write a program to convert distance from Mile to kilometres.
Source Code:
miles = float(input("Enter distance in miles: "))
kilometers = miles * 1.60934
print("Distance in kilometers: ", kilometers)

Output:

K. References / Suggestions
1. https://www.tutorialspoint.com/python/python_numbers.htm
2. https://www.programiz.com/python-programming
3. https://www.w3schools.com/python/
4. https://www.geeksforgeeks.org/python-programming-language/

L. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.8: Identify whether the scanned number is even or odd and print an appropriate
message.

A. Objective:

Make a use of Conditional structures like if else.

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


Ablity to use Conditional structures like if else
D. Expected Course Outcomes(Cos)

CO3
E. Practical Outcome(PRo)
Print even or odd numbers.
F. Expected Affective domain Outcome(ADos)
Follow ethical practices
G. Program Code and Theory:
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"

# Get user input


number = int(input("Enter a number: "))

# Check if the number is even or odd


result = check_even_odd(number)

# Print the appropriate message


print("The number is", result)
PythonProgramming(4311601)

Explanation:
1. The program defines a function called check_even_odd that takes a number as an
input parameter.
2. Inside the function, it checks if the number is divisible by 2 using the modulo
operator (%). If the remainder is 0, it means the number is even; otherwise, it is odd.
3. If the number is even, the function returns the string "Even". If the number is odd,
it returns the string "Odd".
4. The program prompts the user to enter a number.
5. The input number is stored in the variable number.
6. The program calls the check_even_odd function, passing the number as an
argument, and assigns the returned result to the variable result.
7. Finally, it prints the appropriate message by concatenating the result with the string
"The number is".
H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Practical related Quiz.
1: Write a python script whether a given number is positive or negative.
Source Code:

number = float(input("Enter a number:"))

if number > 0:
PythonProgramming(4311601)

print("The number is positive.")


elif number < 0:
print("The number is negative.")
else:
print("The number is zero."
PythonProgramming(4311601)

Output:

K. References / Suggestions
1. https://www.tutorialspoint.com/python/python_numbers.htm
2. https://www.programiz.com/python-programming
3. https://www.w3schools.com/python/
4. https://www.geeksforgeeks.org/python-programming-language/
L. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.9: Create a program to find a maximum number among the given three
numbers.

A. Objective:

Use conditional statements using python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Able to apply conditional statements to solve real world problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)

Able to use conditional statements

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Refer Practical – 1 about preparing flowchart and algorithm to find maximum
number.

if..elif..else statement
:Syntax:
if
(expression1):s
tatement(s)
elif
(expression2):sta
tement(s)
elif
(expression3):sta
tement(s)

else:
PythonProgramming(4311601)

statement(s)

Example:
runs=100

if (runs==200):

print ("1 - Got a true expression


value")print (runs)
elif (runs==150):

print ("2 - Got a true expression


value")print (runs)
elif (runs==100):

print ("3 - Got a true expression


value")print (runs)
else:

print ("4 - Got a false expression


value")print (runs)

print("Goodbye!")

H. Experimental set up/ Program Logic-Flow chart :


Refer Practical – 1 for Flow chart

Algorithm to Find the Maximum Number:


Input: Three numbers num1, num2, and num3

1. Start the program.


2. Accept three numbers num1, num2, and num3 from the user.
3. Set a variable max_num to num1. (We assume num1 is the maximum initially.)
4. Compare num2 with max_num. If num2 is greater than max_num, update
max_num to num2.
5. Compare num3 with max_num. If num3 is greater than max_num, update
max_num to num3.
6. The value of max_num is now the maximum among the three numbers.
7. Print the value of max_num as the maximum number.
PythonProgramming(4311601)

8. End the program.


I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code :
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
maximum = max(num1, num2, num3)
print("The maximum number is:", maximum)

L. Input-Output:

Input:
PythonProgramming(4311601)

Output:

M. Practical related Quiz.


1: Create a program to find 2nd largest element from given 10 numbers.

numbers = [12, 45, 8, 32, 19, 67, 23, 56, 15, 72]
numbers.sort(reverse=True)
second_largest = numbers[1]
print("The second largest element is:", second_largest)

2: Write a program to use max() function.

numbers = [5, 12, 9, 42, 7, 21]


maximum = max(numbers)
print("The maximum value in the list is:", maximum)

N. References / Suggestions
https://docs.python.org/3/tutorial/controlflow.html
O. Assessment-Rubrics
PythonProgramming(4311601)

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: ……………
Practical No.10: Develop a program to demonstrate the basic functionalities of a
standard calculator.

A. Objective:

Use of arithmetic operators and conditional statements using python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply arithmetic operators and conditional statements to solve real world
problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)
Development of standard calculator having basic functionalities

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:

Operator Name Example

+ Addition a+b

- Subtraction a–b

* Multiplication a*b

/ Division a/b

% Modulus a%b

** Exponential a ** b

// Floor Division a // b
PythonProgramming(4311601)

Example: Use of Exponential operator


x=2
y=3
print(x ** y)
H. Experimental set up/ Program Logic-Flow chart :
Use following steps :
1. Start the program.
2. Display the calculator menu with options for addition, subtraction,
multiplication, division, and exit.
3. Prompt the user to choose an option from the menu.
4. If the user chooses "Exit," end the program.
5. If the user chooses any operation (Add, Subtract, Multiply, or Divide):
1. Prompt the user to enter the first number.
2. Prompt the user to enter the second number.
3. Perform the selected operation on the two numbers.
4. Display the result of the operation.
6. If the user enters an invalid option, display an error message and return to the
menu.
7. Repeat steps 2-6 until the user chooses to exit the program.
8. End the program.
I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
PythonProgramming(4311601)

Ensure that all the necessary equipment and software are in good working
condition.
K. Source code :

first = (input("Enter first number : "))


operator = input("Enter Operator (+,-,*,/,%)")
second = (input("Enter second number : "))
first = float(first)
second = float(second)
if operator == "+" :
print(first + second)
elif operator == "-" :
print(first - second)
elif operator == "*" :
print(first * second)
elif operator == "/" :
print(first / second)
elif operator == "%" :
print(first % second)
else :
print("Invalid Operator")

L. Input-Output:

Input:
Enter first number: 5
Enter Operator (+,-,*,/,%): *
Enter second number: 4

Output: 20.0

M. Practical related Quiz.


1: Create a program to check whether a given number is odd or even.

number = int(input("Enter a number: "))

if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd."
PythonProgramming(4311601)

N. References / Suggestions

Refer https://docs.python.org/3/library/math.html for more in built mathematical


functions
O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.11: Write a python program to print 1 to 10 numbers using loops.

A. Objective:
Use of various loops using python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply various looping constructs to solve real world problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)
Print 1 to 10 numbers using loops

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
range() function: Returns sequence of numbers starting from 0.
Loop is used to execute block of statements repeatedly.
1. while loop

Syntax: Example:
while expression: count = 0
statement(s) while(count < 3):
print("Hello World")
count = count + 1

2. for loop

Syntax: Example:
PythonProgramming(4311601)

for iterator_var in sequence: for i in range(3):

statements(s) print("Hello World")

H. Experimental set up/ Program Logic-Flow chart :


Step 1: Start
Initialize variable count to 1, count =1
Step 2: Output count
Step 3: Increment count by 1
count = count +1
Step 4: Check if the value of count is less than or equal to 10. IF count <=10 THEN
GOTO step 2 otherwise GOTO Step 5
Step 5: Stop.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code:

for i in range(1, 11):


print(i)
PythonProgramming(4311601)

L. Input-Output:

Input:

Output:

M. Practical related Quiz.


1: Create a program to print numbers from 1 to 50 in reverse order.

for i in range(50, 0, -1):


print(i)
PythonProgramming(4311601)

N. References / Suggestions
https://wiki.python.org/moin/ForLoop
O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.12: Develop a program to find odd and even numbers from 1 to N numbers.
(Where N is an integer number)

A. Objective:

Use of various loops and conditional statements using python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply various looping constructs with conditional statements to solve real
world problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)
Print odd and even numbers between 1 to N numbers (where N is an integer
number) using loops

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Modulo Division:
The modulo operator % in Python is used for finding the remainder of the division
between two numbers. It is particularly useful for determining if a number is even
or odd. The syntax for the modulo operator is a % b, where a is the dividend and b
is the divisor. The result of a % b is the remainder of the division of a by b.
If-Else Statements:
The if-else statement is used for conditional execution in Python. It allows you to
execute certain code blocks based on specific conditions. The basic syntax of an if-
else statement is:
PythonProgramming(4311601)

if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :
N = int(input("Enter a positive integer N: "))

odd_numbers = []
even_numbers = []

for i in range(1, N + 1):


if i % 2 == 0:
even_numbers.append(i)
else:
odd_numbers.append(i)

print("Odd numbers: ", odd_numbers)


print("Even numbers: ", even_numbers
PythonProgramming(4311601)

K. Input-Output:

Input: Enter a positive integer N: 10

Output:Odd numbers: [1, 3, 5, 7, 9]


Even numbers: [2, 4, 6, 8, 10]

L. Practical related Quiz.


1: Create a program to count odd numbers between 1 to 50.
count = 0
for number in range(1, 51):
if number % 2 != 0:
count += 1

print("The count of odd numbers between 1 and 50 is:", count)

M. References / Suggestions
https://wiki.python.org/moin/ForLoop
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic


PythonProgramming(4311601)

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.13: Write a program to show whether the entered number is prime or not

A. Objective:
Use of various loops, arithmetic operators and conditional statements using
python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Able to apply various looping constructs, arithmetic operators with conditional
statements to solve real world problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)
To show whether the entered number is prime or not

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Prime Number: A prime number is a natural number greater than 1, which is only
divisible by 1 and itself. For example, 2, 3, 5,7, 11, 13 ……
Checking Prime Numbers:
To determine whether a given number is prime or not, you need to check if it has
any divisors other than 1 and itself. One common approach to check for prime
numbers is to iterate from 2 to the square root of the number (since any factor
greater than the square root will have a corresponding factor smaller than the
square root). If you find any divisor within this range, the number is not prime.
Otherwise, it is prime.
Write algorithm to check whether given number is prime or not
PythonProgramming(4311601)

H. Resources/Equipment Required

Sr. Instrument/Equipment Specification Quantity


No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :
def is_prime(number):
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False

i=5
PythonProgramming(4311601)

while i * i <= number:


if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True

try:
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
except ValueError:
print("Invalid input. Please enter a valid number."
PythonProgramming(4311601)

Input: Enter a number: 17

Output: 17 is a prime number.

K. Practical related Quiz.


1: Create a program to print sum of all prime numbers between 1 to 40.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

sum_of_primes = 0
for i in range(2, 41):
if is_prime(i):
sum_of_primes += i

print("The sum of prime numbers between 1 and 40 is:", sum_of_primes)

L. References / Suggestions
https://wiki.python.org/moin/ForLoop
M. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date………….

Practical No.14: Create a program to display the following patterns

A) B)
1 *****
12 ****
123 ***
1234 **
12345 *

A. Objective:

Use of various loops and conditional statements using python

B. Expected Program Outcomes (POs)


PO1, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Able to apply various looping constructs with conditional statements to solve real
world problems

D. Expected Course Outcomes(Cos)


CO3
E. Practical Outcome(PRo)
To print various patterns

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Refer Practical 9, 11
Nested Loops:
Both patterns require the use of nested loops. A nested loop is a loop inside another
loop. The outer loop controls the number of rows, while the inner loop controls the
number of elements in each row.
Algorithm to Create Pattern A:
PythonProgramming(4311601)

Input: Number of rows N for Pattern A


1. Start the program.
2. Accept the number of rows N for Pattern A from the user.
3. Create a function called pattern_a(N) to generate Pattern A.
4. Inside the pattern_a(N) function:

Use nested loops to iterate over rows and columns.


In the outer loop, iterate from i = 1 to N (inclusive).
In the inner loop, iterate from j = 1 to i (inclusive).
Print the value of j followed by a space to create the pattern.
5. Call the pattern_a(N) function to generate and display Pattern A.
6. End the program.

Algorithm to Create Pattern B:


Input: Number of rows N for Pattern B
1. Start the program.
2. Accept the number of rows N for Pattern B from the user.
3. Create a function called pattern_b(N) to generate Pattern B.
4. Inside the pattern_b(N) function:
Use nested loops to iterate over rows and columns.
In the outer loop, iterate from i = N to 1 (inclusive) with a step of -1.
In the inner loop, iterate from j = 1 to i (inclusive).
Print an asterisk * followed by a space to create the pattern.
5. Call the pattern_b(N) function to generate and display Pattern B.
6. End the program.
H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
PythonProgramming(4311601)

Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :

A)
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=' ')
print()

B)
for i in range(n, 0, -1):
for j in range(i):
print("*", end=" ")
print()

K. Input-Output:

Input:

Output:

L. Practical related Quiz.


1: Create a program to print following pattern
AAAAA
AAAA
AAA
AA
A

n=5
for i in range(n, 0, -1):
print('A' * i)
PythonProgramming(4311601)

M. References / Suggestions
https://wiki.python.org/moin/ForLoop
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.15: Create a user-defined function to print the Fibonacci series of 0 to N numbers.
(Where N is an integer number and passed as an argument)

A. Objective:

Use of various loops and user defined functions using python

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply various looping constructs and creating user defined functions to
solve real world problems

D. Expected Course Outcomes(Cos)


CO4
E. Practical Outcome(PRo)
Create a user-defined function to print the Fibonacci series of 0 to N numbers.
(Where N is an integer number and passed as an argument)

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
The Fibonacci series is a sequence of numbers where each number is the sum of the
two preceding ones, starting from 0 and 1. The first few numbers in the Fibonacci
series are 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
User Defined Function – Any function written by us is called user defined function.
● In python, def keyword is used to declare such functions
● An indented block of statements follows the function name and
parameters which contains the body of the function.
Syntax: # Declaring a function
def function_name(): def myFun():
statements print("function body")
PythonProgramming(4311601)

# Calling
functionmyFun()

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :

def fibonacci_series(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

N = 10 # Change N to the desired number


fibonacci_series(N)
PythonProgramming(4311601)

K. Input-Output:

Input: The value of N is set to 10 in the program.

Output: 0 1 1 2 3 5 8 13 21 34

L. Practical related Quiz.


1: Create a user defined function that to print square root of the given number

M. References / Suggestions
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.16: Develop a user-defined function to find the factorial of a given
number.

A. Objective:

Use of various loops and user defined functions using python

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Able to apply various looping constructs and creating user defined functions to
solve real world problems

D. Expected Course Outcomes(Cos)


CO4
E. Practical Outcome(PRo)
Develop a user-defined function to find the factorial of a given number.

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Understanding loops, refer practical – 11, 15
The factorial of a non-negative integer n is the product of all positive integers less
than or equal to n. It is denoted by n!.
For example:
Factorial of 0 is 1: 0! = 1
Factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120: 5! = 120
H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
PythonProgramming(4311601)

1 Computer system OS: Windows 7 or higher Ver., 01


macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :

def calculate_factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
elif n == 0:
return 1
else:
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial

num = int(input("Enter a non-negative integer: "))

result = calculate_factorial(num)
print(f"The factorial of {num} is {result}"
PythonProgramming(4311601)

K. Input-Output:

Input: Enter the value of v = 5

Output: Factorial of 5 is = 120

L. Practical related Quiz.


1: Create a user defined function that to check whether given number is
palindrome or not

def is_palindrome(number):
number_str = str(number)
reversed_str = number_str[::-1]
return number_str == reversed_str

number = 121
result = is_palindrome(number)
if result:
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")

M. References / Suggestions
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total
PythonProgramming(4311601)

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.17: Write a program using the function that reverses the entered value.

A. Objective:
Use of various loops and user defined functions using python

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Able to apply various looping constructs and creating user defined functions to
solve real world problems

D. Expected Course Outcomes(Cos)


CO4
E. Practical Outcome(PRo)
Write a program using the function that reverses the entered value

F. Expected Affective domain Outcome(ADos)


Follow ethical practices
G. Prerequisite Theory:
Reversing a value, such as a number or a string, involves rearranging its elements
in the opposite order.
Following algorithm to reverse the value:
Input: A value (string, number, or any other sequence)

1. Start the program.


2. Accept the input value from the user.
3. Create a function called reverse_value(value).
4. Inside the reverse_value() function:
5. Use slicing with a step of -1 to reverse the input value.
6. Return the reversed value.
7. Call the reverse_value() function, passing the input value as an argument.
8. Print the reversed value.
9. End the program.
PythonProgramming(4311601)

H. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

I. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
J. Source code :
def reverse_string(input_string):
return input_string[::-1]

user_input = input("Enter a value: ")


reversed_value = reverse_string(user_input)
print("Reversed value:", reversed_value)

K. Input-Output:

Input: Enter a value: Hello, World


PythonProgramming(4311601)

Output: Reversed value: !dlroW ,olleH

L. Practical related Quiz.


1: Create a user defined function that to check whether given number is odd or
even.
def is_odd_or_even(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"

# Example usage:
number = 5
result = is_odd_or_even(number)
print(f"{number} is {result}")

M. References / Suggestions
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
N. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: …………
Practical No.18: Write a program that determines whether a given number is an
armstrong number or a palindrome using a user-defined function.

A. Objective:

To check whether the given number is equal to the sum of its own digits raised to
the power of the number of digits
To check whether the given number remains the same when its digits are
reversed.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Understanding of the concept of Armstrong numbers and palindromic numbers.


● Define a function that takes a number as an argument.
● Knowledge of loops, conditional statements, and operators in Python.

D. Expected Course Outcomes(Cos)


CO4
E. Practical Outcome(PRo)
Understanding of the properties of numbers and checking their relationships with
each other to find armstrong numbers or a palindrome.

F. Expected Affective domain Outcome(ADos)

Ensure that specifications for program satisfy the requirements


Ensure adequate testing, debugging and review of code.
G. Prerequisite Theory:
Armstrong Number
Given a number x, determine whether the given number is Armstrong number or
not. A positive integer of n digits is called an Armstrong number of order n (order is
number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
PythonProgramming(4311601)

Input :
153Output:Y
es
153 is an Armstrong
number.1*1*1+5*5*5+3*3*3=153

Input :
120Output:
No
120 is not a Armstrong
number.1*1*1+2*2*2+0*0*0=9

Input :
1253Output:
No
1253isnotaArmstrongNumber
1*1*1*1 +2*2*2*2+5*5*5*5+3*3*3*3= 723

Input :
1634Output:
Yes
1*1*1*1 +6*6*6*6+3*3*3*3+4*4*4*4= 1634
Palindrome Number
A palindrome number is a number that remains the same when its digits are
reversed. For example, 121 is a palindrome number because it reads the same from
left to right and right to left. Palindrome numbers are commonly used in
mathematics and computer science, and they have various applications in these
fields.
To determine whether a given number is a palindrome, we can follow these steps:

Convert the number to a string.

Reverse the string.


Compare the reversed string to the original string.
If they are the same, then the number is a palindrome.

Example:

Enterthenumber:1234
The reverse number
is:4321Thenumberisnotapalindro
me
PythonProgramming(4311601)

Enterthenumber:23434
The reverse number
is:43432Thenumberisnotapalindro
me

H. Experimental set up/ Program Logic-Flow chart :

Algorithm for determining whether a number is an Armstrong number:

Step 1-Define a function called is_armstrong_number that takes one argument, n.


Step 2-Convert n to a string and count the number of digits using len().
Step 3-Initialize a variable called sum to 0.
Step 4-Use a for loop to iterate over each digit in the string.
Step 5-Raise each digit to the power of the number of digits and add it to the sum.
Step 6-If the sum is equal to n, return True. Otherwise, return False.
Algorithm for determining whether a number is an Palindrome number:

Step 1-Read the input number from the user

Step 2-Declare and initialize the variable reverse and assign input to a temp
variable tempNum=num
Step 3-Start the while loop until num !=0 becomes false
rem = num % 10
reverse*= 10 + rem
num = num / 10
Step 4- Check if reverse == tempNum
Step 5-If it’s true then the number is a palindrome
Step 6-If not, the number is NOT a palindrome

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X
PythonProgramming(4311601)

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code:
def is_palindrome(number):
number_str = str(number)
reversed_str = number_str[::-1]
return number_str == reversed_str

number = 121
result = is_palindrome(number)
if result:
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")

L. Input-Output:

Input:The input to the program is the variable number, which is set to the integer
121.

Output 121 is a palindrome:

M. Practical related Quiz.


1: Create a program to find Armstrong numbers in an Interval of 1 to 200.
def is_armstrong(number):
num_str = str(number)
num_digits = len(num_str)
sum_of_cubes = sum(int(digit) ** num_digits for digit in num_str)
return number == sum_of_cubes

start = 1
end = 200
PythonProgramming(4311601)

armstrong_numbers = [num for num in range(start, end + 1) if is_armstrong(num)]


print("Armstrong numbers in the interval from", start, "to", end, "are:",
armstrong_numbers)
PythonProgramming(4311601)

2: Write a program to check if a given word is palindrome or not.


def is_palindrome(word):
word = word.lower()
return word == word[::-1]

input_word = input("Enter a word: ")


if is_palindrome(input_word):
print(f"{input_word} is a palindrome.")
else:
print(f"{input_word} is not a palindrome.")

N. References / Suggestions
https://www.youtube.com/watch?v=fdxtmMOfdrc
https://youtu.be/uUIucXNMEKc
https://youtu.be/IvblQdIwFQI?list=PLgwJf8NK-2e5pY2eB-Lht2_CerQue0Xo4
https://www.geeksforgeeks.org/python-program-to-check-armstrong-number/
https://www.geeksforgeeks.org/check-if-a-number-is-palindrome/

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total
PythonProgramming(4311601)

Sign with Date


PythonProgramming(4311601)

Date: ……………
Practical No.19: Write a program to find the length of a string.

A. Objective:

To find string length in python.


To explore built-in functions for string length

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Knowledge of basic string manipulation in Python, including slicing, indexing, and
concatenation.
● Familiarity with string methods in Python, such as len(), strip(), and join().
● Ability to iterate over a string using loops and comprehension methods.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
A program to find the length of a string
F. Expected Affective domain Outcome(ADos)
Ensure that specifications for program satisfy the requirements
Ensure adequate testing, debugging and review of code.
G. Prerequisite Theory:
This type of problem can be solve using several different approaches, some of them
are:
1. Using len() function
2. Using loop and a counter variable

1. Python len() Function


len() is a built-in function in python. You can use the len() to get the length of the
given string, array, list, tuple, dictionary, etc. You can use the len function to
optimize the performance of the program. The number of elements stored in the
object is never calculated, so len helps provide the number of elements.

Syntax:
len(value)
PythonProgramming(4311601)

Parameters:
● Value: the given value you want the length of.
● Return value
It will return an integer value i.e. the length of the given string, or array, or
list or collections.
Various types of Return values:
- Strings:
It returns the number of characters in a string, which includes
punctuation, space, and all types of special characters. However, you
should be very careful while using len of a Null variable.
- Empty:
Empty is a second return call which has zero characters, but it is
always None.
- Collections:
The len built-in returns the number of elements in a collection.
- TypeError:
Len function depends on the type of the variable passed to it. A Non-
Type does not have any built-in support.
- Dictionary:
For the dictionary, each pair is counted as one unit. However, values
and keys are not independent.

H. Experimental set up/ Program Logic-Flow chart :

Program to find the length of string using library function

Look at the program to understand the implementation of the above-mentioned


approach.

# length of string#
usinglen()

s= "Welcome to
India"print("Sizeofstring:",len(
s))

Output:

Sizeofstring:16
PythonProgramming(4311601)

In the second approach, the program will iterate over the entire string using a loop
and will count the characters with the help of a counter variable. The value of the
counter variable will be the length of the string.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Define a function that will calculate the length of the string
Step 2- Declare and initialize a counter variable
Step 3- Run a loop and iterate over the string
Step 4- Increase the counter variable for every iteration
Step 5- Return counter
Step 6- Call function and print the value

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code:

def find_string_length_len(string):
length = len(string)
return length
PythonProgramming(4311601)

def find_string_length_loop(string):
counter = 0
for char in string:
counter += 1
return counter

input_string = input("Enter a string: ")

length_using_len = find_string_length_len(input_string)
print("Length of the string using len() function:", length_using_len)

length_using_loop = find_string_length_loop(input_string)
print("Length of the string using a loop and counter variable:", length_using_loop
PythonProgramming(4311601)

L. Input-Output:

Input:

Output:

M. Practical related Quiz.


1: How to find the length of the list in python?
You can find the length of a list in Python using the `len()` function. Here's an
example
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("The length of the list is:", length)

2: How to find the length of string while loop and slicing concept?
my_string = "Hello, World!"
count = 0
while my_string:
count += 1
my_string = my_string[1:]
print(count)This code accomplishes the same task of finding the length of a string
using a while loop and slicing without the comments
PythonProgramming(4311601)

N. References / Suggestions
https://www.youtube.com/watch?v=bCdZWZppHLo
https://www.youtube.com/watch?v=HXvoj0u9aMw
https://www.geeksforgeeks.org/python-string-length-len/
https://www.programiz.com/python-programming/string

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Date: ……………
Practical No.20: Write a program to reverse words in a given sentence.

A. Objective:

To reverse each word in a given sentence and explore the built in functions of
string length in python.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Understanding of basic Python syntax and data types (such as strings, lists, and
dictionaries).
● Knowledge of string manipulation in Python, including slicing, indexing, and
concatenation.
● Familiarity with string methods in Python, such as split() and join().
● Ability to iterate over a string or list using loops and comprehension methods.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
A program to reverse words in a given sentence.
F. Expected Affective domain Outcome(ADos)
Ensure that specifications for program satisfy the requirements
Ensure adequate testing, debugging and review of code.

G. Prerequisite Theory:
This type of problem can be solve using several different approaches, some of them
are:

1. Using the slicing method and join functions


2. Using string traverse methods
PythonProgramming(4311601)

1. Python String split() method


Python String split() method in Python split a string into a list of strings after
breaking the given string by the specified separator.
Syntax of String split()
str.split(separator, maxsplit)
split() Parameters
The split() method takes a maximum of 2 parameters:

separator (optional)- Delimiter at which splits occur. If not provided, the string is
splitted at whitespaces.
maxsplit (optional) - Maximum number of splits. If not provided, there is no limit
on the number of splits.

split() Return Value


The split() method returns a list of strings.

2. Python String split() method


join() is an inbuilt string function in Python used to join elements of the sequence
separated by a string separator. This function joins elements of a sequence and
makes it a string.

Syntax: string_name.join(iterable)

Parameters:

Iterable – objects capable of returning their members one at a time. Some


examples are List, Tuple, String, Dictionary, and Set
Return Value: The join() method returns a string concatenated with the elements
of iterable.

H. Experimental set up/ Program Logic-Flow chart :

Program to reverse words in a given sentence using library function

Look at the program to understand the implementation of the above-mentioned


approach.
PythonProgramming(4311601)

#pythoncodetoreversewordsinagivenstring

#inputstring
string= "ilikepythonprogramverymuch"

# spliting words in the given


string#usingslicingreversethewords
s=string.split()[::-1]

# joining the reversed string and#


printingtheoutput
print("".join(s))

Output:

muchveryprogrampythonlikei

In the second approach, Follow the below steps to solve the problem:

● Run a for loop to traverse the string and create a temporary string to store the
words
● If the current character is a space then add the current string to the answer and
empty the string
● Else push the character into the string
● Print the answer array in reverse order

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X
PythonProgramming(4311601)

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.

K. Source code:

def reverse_words(sentence):
words = sentence.split()
reversed_words = list(reversed(words))
reversed_sentence = ' '.join(reversed_words)
return reversed_sentence

input_sentence = "Hello, world!"


output_sentence = reverse_words(input_sentence)
print(output_sentence)

L. Input-Output:

Input:
PythonProgramming(4311601)

Output: world! Hello,

M. Practical related Quiz.


1: How to Split a string on a $ character?

text = "This$is$a$string"
parts = text.split('$')
print(parts)

2: Join the list's elements with: "+++".

my_list = ["element1", "element2", "element3"]


result = "+++".join(my_list)
print(result)
PythonProgramming(4311601)

N. References / Suggestions

https://www.youtube.com/watch?v=UVRVF1TtXAo
https://www.geeksforgeeks.org/reverse-words-in-a-given-string/
https://www.programiz.com/python-programming/methods/string/split

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.21: Write a program to check if a substring is present in a given string.

A. Objective:
To check if a substring is present in a given sentence or not.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Knowledge of slicing and indexing operations in Python.
● Familiarity with basic string operations, such as concatenation, splitting, and
replacing.
● Ability to write conditional statements to check for the existence of substrings
within a string.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
A program to check if a substring is present in a given string.
F. Expected Affective domain Outcome(ADos)
Improve ability to create reliable, and useful python code.
Ensure adequate testing, debugging and review of code.
G. Prerequisite Theory:
Given two strings, check if a substring is there in the given string or not.

Example 1: Input : Substring = "Python"


String="I like Python Programming"
Output : Yes

Example 2: Input : Substring = "Java"


String="I like Python Programming"
PythonProgramming(4311601)

Output : No

Checking a substring is one of the most used tasks in python. Python uses many
methods to check a string containing a substring like, find(), index(), count(), etc.
The most efficient and fast method is by using an “in” operator which is used as a
comparison operator.

This type of problem can be solve using several different approaches, some of them
are:
● Checking using the split() method
● Using find() method
● Using the if… in

H. Experimental set up/ Program Logic-Flow chart :

First split the given string into words and store them in a variable then using the if
condition, check if a substring is present in the given string or not.

#inputstringsstr1andsubstr
string = "I like Python
Programming"substring="Python"#orsubstring=
input()# splittingwords ina givenstring
s=string.split()
#checkingcondition
#ifsubstringispresentinthegiven stringthenitgivesoutputasyesif substring
ins:
print("yes")e
lse:
print("no")

Output:

yes

In the second approach, Follow the below steps to solve the problem:

Algorithm to check if a substring is present in a given string using the find()


method:
● Get the input for the main string and the substring from the user.
PythonProgramming(4311601)

● Use the find() method to search for the substring in the main string. The find()
method returns the index of the first occurrence of the substring in the main string,
or -1 if the substring is not present in the main string.
● Check the return value of the find() method. If it is not -1, then the substring is
present in the main string. If it is -1, then the substring is not present in the main
string.

Algorithm to check if a substring is present in a given string using the in operator:

● Get the input for the main string and the substring from the user.
● Use the in operator to check if the substring is present in the main string.
● Check the return value of the in operator. If it is True, then the substring is present
in the main string. If it is False, then the substring is not present in the main string.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code:

main_string = input("Enter the main string: ")


substring = input("Enter the substring to search for: ")
index = main_string.find(substring)
if index != -1:
print(f"The substring '{substring}' is present in the main string at index {index}.")
else:
print(f"The substring '{substring}' is not present in the main string.")
PythonProgramming(4311601)

L. Input-Output:

Input:

Output: 'world' is present in the string.

M. Practical related Quiz.


1: How do you count the number of occurrences of a substring in a given string in
Python?

main_string = "Hello, Hello, Hello, World!"


substring = "Hello"
count = main_string.count(substring)
print(count) # Output:
PythonProgramming(4311601)

2: What is the difference between slicing and indexing when working with
substrings in Python?

Indexing is used to access a single element at a specific position in a


sequence, while slicing is used to extract a portion of a sequence, creating
a new sequence that includes a range of elements.

N. References / Suggestions

https://www.youtube.com/watch?v=xVh59g7EiM0
https://www.digitalocean.com/community/tutorials/python-string-substring
https://www.freecodecamp.org/news/how-to-substring-a-string-in-python/

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.22: Write a program to count and display the number of vowels, consonants,
uppercase, lowercase characters in a string.

A. Objective:

To identify and count the number of vowels, consonants, uppercase letters, and
lowercase letters in the string and display the results to the user.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Knowledge of basic string manipulation in Python, including slicing, indexing, and


concatenation.
● Familiarity with string methods in Python, such as lower(), upper(), isalpha(), and
isdigit().
● Ability to write functions to count and display the number of vowels, consonants,
uppercase, lowercase characters in a string based on specific criteria.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
Counting and displaying the number of vowels, consonants, uppercase, and
lowercase characters in a data is a fundamental analysis task that can be applied to
a wide range of use cases.
F. Expected Affective domain Outcome(ADos)
Improve ability to create reliable, and useful python code.
Ensure adequate testing, debugging and review of code.
1. Follow safety practices.
2. Practice good housekeeping
3. Demonstrate working as a leader/ a team member.
4. Follow ethical practices.
PythonProgramming(4311601)

G. Prerequisite Theory:
isupper()
In Python, isupper() is a built-in method used for string handling. This method
returns True if all characters in the string are uppercase, otherwise, returns “False”.

1. It returns “True” for whitespaces but if there is only whitespace in the


string then returns “False”.
2. It does not take any arguments, Therefore, It returns an error if a
parameter is passed.
3. Digits and symbols return “True” but if the string contains only digits and
numbers then returns “False”
This function is used to check if the argument contains any uppercase characters
such as :

Input: string = 'IT DEPARTMENT'


Output: True

Input: string = 'It Department'


Output: False
Syntax of isupper()
Syntax: string.isupper()

Parameters:

isupper() does not take any parameters


Returns:
True- If all characters in the string are uppercase.
False- If the string contains 1 or more non-uppercase characters.

islower()

The islower() method returns True if all characters in the string are lowercase,
otherwise, returns “False”.

1. It returns “True” for whitespaces but if there is only whitespace in the


string then returns “False”.
2. It does not take any arguments, Therefore, It returns an error if a
parameter is passed.
3. Digits and symbols return “True” but if the string contains only digits and
numbers then returns “False”.
PythonProgramming(4311601)

This function is used to check if the argument contains any lowercase characters
such as :

Input: string = 'geeksforgeeks'


Output: True

Input: string = 'GeeksforGeeks'


Output: False
Syntax of islower()
Syntax: string.islower()

Parameters:

islower() does not take any parameters


Returns:

True- If all characters in the string are lower.


False- If the string contains 1 or more non-lowercase characters.

isalpha()
Python String isalpha() method is used to check whether all characters in the
String is an alphabet.

Python String isalpha() Method Syntax:


Syntax: string.isalpha()

Parameters: isalpha() does not take any parameters

Returns:

True: If all characters in the string are alphabet.


False: If the string contains 1 or more non-alphabets.
Errors and Exceptions:

It contains no arguments, therefore an error occurs if a parameter is passed


Both uppercase and lowercase alphabets return “True”
Space is not considered to be the alphabet, therefore it returns “False”

Python String isalpha() Method Example:


string = "itdepartment"
print(string.isalpha())

Output: True
PythonProgramming(4311601)

H. Experimental set up/ Program Logic-Flow chart :

Here is a possible algorithm for a program to count and display the number of
vowels, consonants, uppercase, lowercase characters in a string:

Get the input string from the user.


Initialize variables to store the count of vowels, consonants, uppercase letters,
and lowercase letters to zero.
Loop through each character in the input string:
a. Check if the character is a vowel (a, e, i, o, u or A, E, I, O, U). If it is, increment
the vowel count variable.
b. Check if the character is a consonant (not a vowel and not a space). If it is,
increment the consonant count variable.
c. Check if the character is an uppercase letter. If it is, increment the uppercase
count variable.
d. Check if the character is a lowercase letter. If it is, increment the lowercase
count variable.
Display the counts of vowels, consonants, uppercase letters, and lowercase letters
to the user.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
PythonProgramming(4311601)

K. Source code:

def count_characters(string):
vowels_count = 0
consonants_count = 0
uppercase_count = 0
lowercase_count = 0

vowels = set("AEIOUaeiou")

for char in string:


if char.isalpha():
if char in vowels:
vowels_count += 1
else:
consonants_count += 1

if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

print("Vowels:", vowels_count)
print("Consonants:", consonants_count)
print("Uppercase Characters:", uppercase_count)
print("Lowercase Characters:", lowercase_count)

input_string = input("Enter a string: ")


count_characters(input_string)
PythonProgramming(4311601)

L. Input-Output:

Input: Marvel studios

Output:
Vowels: 5
Consonants: 8
Uppercase Characters: 1
Lowercase Characters: 12
PythonProgramming(4311601)

M. Practical related Quiz.


1: Develop a program to convert camel case string to snake case.
Input :ThisIsInCamelCase
Output :this_is_in_camel_case
import re
def camel_to_snake(input_str):
snake_case_str = re.sub('([A-Z])', r'_\1', input_str)
return snake_case_str.lower().lstrip('_')

input_str = "ThisIsInCamelCase"
output_str = camel_to_snake(input_str)
print(output_str)

2: Explain upper(), lower() methods in Python

1. upper(): Converts all letters in a string to uppercase.


• Example: "hello".upper() returns "HELLO".
2. lower(): Converts all letters in a string to lowercase.
• Example: "WORLD".lower() returns "world".
PythonProgramming(4311601)

N. References / Suggestions
https://www.youtube.com/watch?v=ikG9DoACpJM
https://www.geeksforgeeks.org/isupper-islower-lower-upper-python-
applications/?ref=rp
https://codescracker.com/python/program/python-count-characters-in-text-
file.htm

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.23: Develop programs to perform the following list operations.
a)To swap given two elements in a list.
b)To find the sum of elements in a list.

A. Objective:
To modify the original list by swapping the elements, and to calculate the total
value of all the elements in the list.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Familiarity with the concept of temporary variables and their use in swapping
values.
● Ability to handle edge cases, such as swapping elements at the beginning or end
of a list.
● Ability to iterate over all elements in a list and sum them up.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
Swapping elements in a list allows for the manipulation and reordering of data
within the list, while finding the sum of elements in a list allows for analysis of the
data within the list.
F. Expected Affective domain Outcome(ADos)
Improve ability to create reliable, and useful python code.
Ensure adequate testing, debugging and review of code.
1. Follow safety practices.
2. Demonstrate error free code.
3. Follow ethical practices.
PythonProgramming(4311601)

G. Prerequisite Theory:
pop()

Python list pop() is an inbuilt function in Python that removes and returns the last
value from the List or the given index value.

Python List pop() Method Syntax


Syntax: list_name.pop(index)

index (optional) – The value at index is popped out and removed. If the index is not
given, then the last element is popped out and removed.

Return: Returns The last value or the given index value from the list.
Using List pop() method to pop an element at the given index

list1 = [1, 2, 3, 4, 5, 6]

print(list1.pop(), list1)
print(list1.pop(0), list1)

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

sum()
Python provides an inbuilt function sum() which sums up the numbers in the list.

Syntax:
sum(iterable, start)

iterable :iterable can be anything list , tuples or dictionaries ,but most importantly
it should be numbers.
start : this start is added to the sum of numbers in the iterable.
If start is not given in the syntax , it is assumed to be 0.
Possible two syntaxes:

sum(a)
a is the list , it adds up all the numbers in the list a and takes start to be 0, so
returning only the sum of the numbers in the list.
sum(a, start)
PythonProgramming(4311601)

this returns the sum of the list + start


Below is the Python implementation of the sum()

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

# start parameter is not


providedSum =sum(numbers)
print(Sum)

# start =10
Sum = sum(numbers,
10)print(Sum)

output
25
35

Using list comprehension


list1 =[12, 15,3,10]
s=[i for i in
list1]print(sum(s)
)

output
40

H. Experimental set up/ Program Logic-Flow chart :

● To swap given two elements in a list.


To execute this task we can follow multiple approaches, some are discussed
below-

● By using pop() function to pop the elements at the given position.


● By using a third variable for swapping the values present at the given
indexes.
PythonProgramming(4311601)

Approach #1 : Using Inbuilt list.pop() function


Pop the element at pos1 and store it in a variable. Similarly, pop the element at
pos2 and store it in another variable. Now insert the two popped element at each
other’s original position.

defswapPositions(list,pos1,pos2):
#poppingboththeelementsfromlistfirst_e
le =list.pop(pos1)
second_ele=list.pop(pos2-1)
#insertingineachotherspositionslist.i
nsert(pos1,
second_ele)list.insert(pos2,first_ele)
returnlist

#DriverfunctionList=[2
3,65,19,90]
pos1, pos2= 1,
3print(swapPositions(List,pos1-1,pos2-1))

Output:

[19,65,23,90]

Approach #2: Swapping using third variable

Algorithm
Step 1- Define a function to swap elements with the list sl and positions pos1 and
pos2 as parameters
Step 2- Swap elements sl[pos1] and sl[pos2] using a third variable
Step 3- Return the swapped list
Step 4- Define the list values and the positions of the elements which have to be
swapped
Step 5- Pass the list and (pos1-1) and (pos2-1) in the function (because indexing
starts from 0) and print the result

● To find the sum of elements in a list.

Algorithm
Step 1-Initialize a variable to hold the sum and set it to 0.
PythonProgramming(4311601)

Step 2-Loop through each element in the list.


Step 3-For each element, add it to the sum variable.
Step 4-After all elements have been looped through, the sum variable will hold
the total sum of all the elements in the list.
Step 5-Return the sum variable.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.

K. Source code:

i)

def swap_elements(lst, pos1, pos2):


if 0 <= pos1 < len(lst) and 0 <= pos2 < len(lst):
temp = lst[pos1]
lst[pos1] = lst[pos2]
lst[pos2] = temp
return lst

values = [1, 2, 3, 4, 5]
pos1 = 1
pos2 = 3
result = swap_elements(values, pos1 - 1, pos2 - 1)
print(result)
PythonProgramming(4311601)

ii)
def find_sum(lst):
total_sum = 0
for element in lst:
total_sum += element
return total_sum

values = [1, 2, 3, 4, 5]
sum_of_elements = find_sum(values)
print("The sum of elements in the list is:", sum_of_elements)

L. Input-Output:

Input:

i) ii)
PythonProgramming(4311601)

Output:

i) [3, 2, 1, 4, 5] ii) The sum of


elements in the
list is: 15
PythonProgramming(4311601)

M. Practical related Quiz.


1:What is the difference between “remove” and “pop” in a list?

The main difference between "remove" and "pop" in a list is that "remove" is used to
remove a specific value from the list and doesn't return the removed value, while "pop" is used to
remove and return an element at a specified index or the last element by default.

my_list = [1, 2, 3, 4, 5]
popped_value = my_list.pop(2) # Removes and returns the element at index 2 (which is 3)
print(popped_value) # 3
print(my_list) # [1, 2, 4, 5]

2: How to manipulate every element in a list with list comprehension

Multiply every element in a list by 2:

original_list = [1, 2, 3, 4, 5]
new_list = [x * 2 for x in original_list]
print(new_list) # Output: [2, 4, 6, 8, 10]
PythonProgramming(4311601)

N. References / Suggestions
https://youtu.be/ORVjpSTXtRI
https://youtu.be/FkQyr_N-G3w
https://www.studytonight.com/python-programs/python-program-to-swap-two-
elements-in-a-list
https://www.geeksforgeeks.org/sum-function-python/

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.24: Develop programs to perform the following list operations.
a)To check if an element exists in a given list.
b)To find the smallest and largest element in a given list.

A. Objective:
To determine if a specific value is included in the list or not and to identify the
extreme values in the list.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:

● Familiarity with Python's built-in functions and methods, such as in.


● Understanding of the concept of variable scope in Python.
● Familiarity with Python control structures, such as if statements.
● Familiarity with Python's built-in functions and methods, such as min and max.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
Checking if an element exists in a list and finding the smallest and largest element
in a list.
F. Expected Affective domain Outcome(ADos)
Improve ability to create reliable, and useful python code.
Ensure adequate testing, debugging and review of code.
1. Follow safety practices.
2. Demonstrate error free code.
3. Follow ethical practices.
G. Prerequisite Theory:
“in” Keyword:
The in keyword has two purposes:
PythonProgramming(4311601)

● To check if a value is present in a list, tuple, range, string, etc.


● To iterate through a sequence in a for loop.
Syntax:

# Using if statement
if ele in seq:
statement(s)

# Using for statement


for ele in seq:
statement(s)

a) To check if an element exists in a given list.

Method 1: Naive Method


In the Naive method, one easily uses a loop that iterates through all the elements
to check the existence of the target element. This is the simplest way to check the
existence of the element in the list. This particular way returns True if an element
exists in the list and False if the element does not exist in the list. The list need not
be sorted to practice this approach of checking.

Example 1: Check if an element exists in the list using the if-else statement

#pythoncode to Checkif element existsinlistornot

lst=[1,6,3,5,3,4]
#checkingifelement7ispresent#
inthegiven listornot
i=7
#ifelementpresentthenreturn#
existotherwisenotexist
if i in
lst:print("exist
")
else:
print("notexist")

output
notexist
PythonProgramming(4311601)

Example 2: Check if an element exists in the list using a loop


#Initializinglist
test_list =[1,6,3,5, 3,4]

# Checking if 4 exists in
listfor iintest_list:
if(i ==
4):print("ElementExists")

output
ElementExists

min() Method
Python list method min() returns the elements from the list with minimum value.

Syntax
Following is the syntax for min() method −
min(list)
Parameters
list − This is a list from which min valued element to be returned.

Return Value
This method returns the elements from the list with minimum value.

Example
The following example shows the usage of min() method.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]print


"minvalue element:",min(list1)
print"minvalueelement:",min(list2)

output
min value element
:123minvalueelement:200

max() Method

Python list method max returns the elements from the list with maximum value.
PythonProgramming(4311601)

Syntax
Following is the syntax for max() method −

max(list)
Parameters
list − This is a list from which max valued element to be returned.

Return Value
This method returns the elements from the list with maximum value.

Example
The following example shows the usage of max() method.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]print


"Maxvalueelement :", max(list1)
print"Maxvalueelement :",max(list2)

output
Max value element
:zaraMaxvalueelement:700

H. Experimental set up/ Program Logic-Flow chart :

● To check if an element exists in a list using a loop:


Algorithm
Step 1-Initialize a boolean variable called found to False.
Step 2-Start a loop that will iterate through each element in the list.
Step 3-For each element in the list, check if it matches the element you are
looking for.
Step 4-If the element matches, set found to True and break out of the loop.
Step 5-If the loop finishes without finding a match, found will still be False.
Step 6-Return the value of found.

● To find the smallest and largest element in a given list.


Algorithm
Step 1-Initialize two variables, smallest and largest, to the first element in the list.
Step 2-Iterate over the remaining elements in the list.
PythonProgramming(4311601)

Step 3-For each element, compare it to the current smallest and largest values.
Step 4-If the element is smaller than the current smallest, update smallest to the
element.
Step 5-If the element is larger than the current largest, update largest to the
element.
Step 6-After iterating over all elements, return smallest and largest.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.

K. Source code:

i)
def element_exists(lst, target):
if target in lst:
return True
else:
return False

# Example usage
my_list = [1, 2, 3, 4, 5]
element_to_check = 3
if element_exists(my_list, element_to_check):
print(f"{element_to_check} exists in the list.")
else:
print(f"{element_to_check} does not exist in the list.")
PythonProgramming(4311601)

ii)
def find_smallest_largest(lst):
if len(lst) == 0:
return None, None # Return None for both smallest and largest if the list is
empty

smallest = lst[0]
largest = lst[0]

for element in lst:


if element < smallest:
smallest = element
elif element > largest:
largest = element

return smallest, largest

# Example usage
my_list = [5, 2, 9, 1, 7, 3]
smallest, largest = find_smallest_largest(my_list)
print(f"The smallest element is {smallest}, and the largest element is {largest}.")
PythonProgramming(4311601)

L. Input-Output:

Input:

i) my_list = [1, 2, 3, 4, 5] iii) my_list = [5, 2, 9, 1, 7, 3]


element_to_check = 3

ii) my_list = [1, 2, 3, 4, 5] iv) my_list = []


element_to_check = 6
PythonProgramming(4311601)

Output:

i) 3 exists in the list. iii) The smallest element is 1, and


the largest element is 9
iv) The list is empty, so both the
ii) 6 does not exist in the list. smallest and largest elements
are None.

M. Practical related Quiz.


1: Develop a program to find second largest number in a list.
def find_second_largest(numbers):
if len(numbers) < 2:
return "List should have at least two numbers"

# Sort the list in descending order


numbers.sort(reverse=True)

# The second largest number will be at index 1 (0-based indexing)


second_largest = numbers[1]

return second_largest

# Example usage:
numbers = [10, 5, 8, 20, 15]
result = find_second_largest(numbers)
print("The second largest number is:", result)
PythonProgramming(4311601)

N. References / Suggestions

https://youtu.be/gfldTt9E3kg
https://www.youtube.com/watch?v=ZP9DlljyzMQ
https://youtu.be/d78Iq79g7xU?list=PLgwJf8NK-2e5pY2eB-Lht2_CerQue0Xo4
https://www.geeksforgeeks.org/check-if-element-exists-in-list-in-python/
PythonProgramming(4311601)

https://www.geeksforgeeks.org/python-program-to-find-smallest-number-in-a-
list/
https://medium.com/programminginpython-com/python-program-to-find-the-
largest-and-smallest-number-in-a-list-fd8fac8aba08
https://www.tutorialspoint.com/python/list_min.htm

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

ate: ……………
Practical No.25:
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of
Python that takes this list and makes a new list that has only the even elements of this list
in it.
b) Create a list containing the square of all odd numbers from range 1 to 10.
c) Create a list of prime and non-prime numbers in range 1 to 50.

A. Objective:
To filter out the odd elements from the list and create a new list containing only
the even elements
To create a list of the squares of odd numbers within a specific range
To identify and distinguish between prime and non-prime numbers within a
specific range.

B. Expected Program Outcomes (POs)


PO2, PO3, PO4, PO6, PO7

C. Expected Skills to be developed based on competency:


● Familiarity with Python control structures, such as loops and if statements.
● Ability to write simple Python functions.
● Ability to iterate over all elements in a list.

D. Expected Course Outcomes(Cos)


CO5

E. Practical Outcome(PRo)
Swapping elements in a list allows for the manipulation and reordering of data
within the list, while finding the sum of elements in a list allows for analysis of the
data within the list.
F. Expected Affective domain Outcome(ADos)
Improve ability to create reliable, and useful python code.
Ensure adequate testing, debugging and review of code.
1. Follow safety practices.
2. Demonstrate error free code.
3. Follow ethical practices.
PythonProgramming(4311601)

G. Prerequisite Theory:
list comprehension
A Python list comprehension consists of brackets containing the expression, which
is executed for each element along with the for loop to iterate over each element
in the Python list.

Python List comprehension provides a much more short syntax for creating a new
list based on the values of an existing list.

Advantages of List Comprehension


More time-efficient and space-efficient than loops.
Require fewer lines of code.
Transforms iterative statement into a formula.
Syntax of List Comprehension
newList = [ expression(element) for element in oldList if condition ]

Example of List Comprehension in Python


Example 1: Iteration with List comprehension

#UsinglistcomprehensiontoiteratethroughloopList
=[characterfor character in[1, 2,3]]

# Displaying
listprint(List)

output

[1, 2,3]

Example 2: Odd list using list comprehension

list =[iforiinrange(11)ifi%2
!=0]print(list)

output

[1, 3,5,7,9]
PythonProgramming(4311601)

Example 3: Nested IF with List Comprehension

num_list =[yforyinrange(100) ify


%2==0ify%5==0]print(num_list)

output

[0,10,20,30,40,50,60,70, 80,90]

Example 4: if...else With List Comprehension

obj=["Even"if i%2==0else"Odd"foriinrange(10)]print(obj)

output

['Even','Odd','Even','Odd','Even','Odd','Even','Odd','Even','Odd']

H. Experimental set up/ Program Logic-Flow chart:


● To makes a new list that has only the even elements of this list in it

Algorithm

Step 1-Use a list comprehension to filter out the odd elements from the original
list and create a new list containing only the even elements.
Step 2-Return the new list containing only the even elements.

● Create a list containing the square of all odd numbers from range 1 to 10.

Algorithm
Step 1- Use a list comprehension to iterate through each number from 1 to 10 and
filter out the even numbers using an if statement.
Step 2- Square each odd number using the power operator ** and add it to the
new list.
Step 3- Return the list containing the squares of odd numbers.
PythonProgramming(4311601)

● Create a list of prime and non-prime numbers in range 1 to 50.

Algorithm
Step 1- Use a nested list comprehension to iterate through each number from 1 to
50 and check if it's prime or not using another nested list comprehension and the
modulo operator.
Step 2- Append the prime numbers to one list and the non-prime numbers to
another list.
Step 3- Return both lists containing the prime and non-prime numbers.

I. Resources/Equipment Required
Sr. Instrument/Equipment Specification Quantity
No. /Components/Trainer kit
1 Computer system OS: Windows 7 or higher Ver., 01
macOS, and Linux, with 4GB or
higher RAM
2 Python IDEs Open Source : IDLE, Jupyter 01
Python versions: 2.7.X, 3.6.X

J. Safety and necessary Precautions followed


Use the most recent version of Python
Use built-in functions and libraries
Read the experiment thoroughly before starting and ensure that you
understand all the steps and concepts involved from underpinning theory.
Keep the workspace clean and organized, free from clutter and
unnecessary materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
K. Source code:

i)
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
even_elements = [x for x in a if x % 2 == 0]
print(even_elements)
PythonProgramming(4311601)

ii)
# Using a list comprehension to create a list of squares of odd numbers
squares_of_odd_numbers = [x**2 for x in range(1, 11) if x % 2 != 0]

# Print the resulting list


print(squares_of_odd_numbers)
PythonProgramming(4311601)

L. Input-Output:

Input:

i) ii) iii)

Output:

i) ii) iii)

M. Practical related Quiz.


1: Write list comprehension to count the number of spaces in a string
PythonProgramming(4311601)

2: Write list comprehension to find all of the numbers from 1-1000 that are
divisible by 7

N. References / Suggestions
https://youtu.be/TGaKzl6p4nA?list=PL98qAXLA6aftqPGddFjJ59m71F96ZPwD4
https://youtu.be/1HlyKKiGg-4
https://www.programiz.com/python-programming/list-comprehension
https://www.w3schools.com/python/python_lists_comprehension.asp

O. Assessment-Rubrics

S. No Rubrics Marks (0-5)

1 Identify suitable approach to implement logic

2 Use pre-built packages/functions

3 Use python concepts to implement efficient program

4 Follow different input test cases to check output

5 Identify and mend coding errors in a program /


Interpret the result and conclude

Total

Sign with Date


PythonProgramming(4311601)

Python Programming
(4311601)
Lab manuals are prepared by
Dr. Lataben J Gadhavi
Lecturer, Information Technology Department
Government Polytechnic Gandhinagar

Dr. Esan P Panchal


Lecturer, Information Technology Department
Government Polytechnic Gandhinagar

Shri. Hardik R Mandora


Lecturer, Information Technology Department
RCTI, Ahmedabad

Branch Coordinator
Shri.Nandu Fatak
Head of Department, Information Technology Department
Government Polytechnic for Girls

Committee Chairman
Shri R. D. Raghani
(HOD-EC)
Principal (I/C)
Government Polytechnic, Gandhinagar

You might also like