0% found this document useful (0 votes)
2K views176 pages

Python Lab Manual by DR Kiransing Pratapsing Paradeshi

This Python Programming Lab Manual is useful for beginners. Especially it is very useful for second year computer science, Electronics and computer science Engineering Electronics Engineering and BSC computer, etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views176 pages

Python Lab Manual by DR Kiransing Pratapsing Paradeshi

This Python Programming Lab Manual is useful for beginners. Especially it is very useful for second year computer science, Electronics and computer science Engineering Electronics Engineering and BSC computer, etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 176

PADMABHOOSHAN VASANTRAODADA PATIL

INSTITUTE OF TECHNOLOGY,

BUDHGAON-416304

DEPARTMENT OF ELECTRONICS AND


COMPUTER SCIENCES ENGINEERING

PYTHON PROGRAMMING LAB


MANUAL

S.Y(ECS) – IV Semester
Year :-2022-23

Subject Incharge :- DR.K.P.Paradeshi

1|Page
Padmabhooshan Vasantraodada Patil Institute of Technology, Budghgaon
Department of Electronics and Computer science

INDEX
Sr. Title of experiment Date Date Page Sign
No. performed submitted no.

1 Introduction of python programming and


installation of python.
2 To study the operators.

3 To study of statement if, elif, nested if, while


loop.
4 To study string and list methods.

5 To study the list operators.

6 To study tuple and its operators and methods.

7 To study dictionary operators.

8 To study python programs using function.

9 To study python program creating the module


and package.
10 To study python program using turtle.

2|Page
CONTENTS
1. Introduction of python programming and installation of python.
1.1 Introduction of python programming and installation of python.

2. To study the operators.


2.1 To write python code to conversion of temperature from Celsius to Fahrenheit.
2.2 Learn a different operators and write python code using ( +, - , / , * ).
2.3 Find out area and parameter of different given geometric shapes using python.

3. To study of statement if, elif, nested if, while loop


3.1 To write a python code to check eligibility of voter using if else.
3.2 To write a python code to find the largest number of 3 numbers using nested if
3.3 To write a program using if -Elif else to find out grade of student when provide the
percentage of mark.
3.4 To write a program to add first 100 numbers using while.
3.5 To write a program using while loop to separate digit from a given number add them to print
result.
3.6 To write a program using white to find out factorial number.

4. To study string and list methods.


4.1 To write the file transport to basic string operations.
4.2 To write a python code to method performed on string.

5. To study the list operators.


5.1 Write a program using list to carry out following operators: create list and print list, Repeat
a particular element in list, Access the element in the list, Loop throughout list to print its element.

5.2 Write a program using list to carry out following operator: Concatenation of list, merging on
list, Cloning and copying of list, searching on element in list, Use comparison operators in list,
Delete the
list element.
5.3 Use built in function and list following methods to find out: Len, Max, Min, Del, Sort, and
Reverse, Use following list method such as ( append, remove, pop, insert, count and index ).

5.4 Performed the following operations on a list of names: Create a list of five names [Anil, Amol,
3|Page
Aditya, Avinash, Ajit], Insert the name [Anuj before Aditya], Append name [Abhijit], Delete
[Avinash] from list,Replace [Anil] with [Anil Kumar], Sort all names in list, Print reverse sorted
list.
5.5 operation on list of numbers: Create a list of five odd numbers, Creator list of five even
numbers,combined two list, Add prime numbers (11, 17 and 29) at the beginning of combined list,
repeat how many elements are present in list, Replace last three numbers of list with (100, 200,
300), Delete all numbers of list, Delete the list

6. To study tuple and its operators and methods


6.1 Write a program in python to create a tuple, empty tuple, mix tuple, and nested tuple, carry
and following operation: Access element in tuple, Use indexing and slicing operation, packing and
unpacking.

6.2 Write a program in python to: Convert tuple to list, Append the element, Add element at
appropriate position, convert back into tuple, Concatenation membership operator, len operators.

6.3 Following tuple is given (A,B,C,D,E,F,G,H,I,E) writer python program to add ! Mark at the
end of tuple Convert tuple to string, Extract ‘B’ from Tuple, find number of occurrences of ‘E’

7. To study dictionary operators


7.1 write a program using dictionary to carry out following operation: create dictionary data structure
and print dictionary, create dictionary which told the data.

7.2 write a program using dictionary to carry out following operation: Create dictionary data
structure and print dictionary, update the element in dictionary, short element in dictionary.

7.3 Use built in function and list following methods to find: Create dictionary data structure and
print dictionary, add the element in dictionary, set the value in the dictionary, sorting the element in
dictionary, delete the element in dictionary.

8. To study python programs using function


8.1 Write a python program to find factorial of given using function.
8.2 Solver using the following series using function ( sum = 4/1! + 3/3! + 5/5! + 7/7! + …….)
8.3 Write the program that define function to count alphabets, writer space and number from a given
string, also major the length of string after subtraction white space.

8.4 create array of 10 numbers and reserve it, wright to function to add and subtract the array
element and print the result, Carry out elementwise multiplication and division also.

9. To study python program creating the module and package


9.1 To write a python code for creating model to find large number out of given three numbers.
9.2 To learn a python code to create packages that perform basic operation on calculator.

4|Page
10. To study python program using turtle
10.1 To write a program for using turtle commands in python to create shapes using turtle.

5|Page
Practical No: 1

Title: Installation of Python IDE’s with several methods.

Aim: To Install python using different methods.

Objectives:
1) To install python by Anaconda distribution package and launching python IDEs
Such as: Spider, Jupyter Notebook and Pycharm (IDE).
2) To install Python (IDLE) using Python.org.

Theory:
Python is an object oriented, interpreted mid-level programming language that is easy to learn
and used for deep learning, machine learning and data science. Python free and open source
programming language it is cross-platform compatibility and has loe system requirements.
Python extensible language. We can right wright program in python into ‘C’ or ‘C++’ language
and also we can compiled it in ‘C’ or ‘C++’.

Anaconda:
Anaconda is free softwre that provides you with toolkit that is for research and science.
Installing Anaconda gives access to different environments that allow to code in either python
or environments, also known an integrated development environment (IDEs). IDEs contain
many useful feature to write, edit and debug code, visualize and inspect data, store variables
present results and collaborate on projects.
Pycharm:
Pycharm is the most popular IDE used for Python scripting language. This will give you and
introduction to pycharm. Pycharm offers you some best features like code completion and
inspection, advanced debugging, Support for web programming and frameworks such as
Django and Flask.
Python IDLE:
IDLE is Python’s intrgrated development and learning environment. IDLE has two window
types, the shell windoe and the eidtor window Python IDLE is easy that it is an appropriate
device for begineer installation’s on windows. It has built in debugger, runs without a server
or browser, It is quite simple and smooth.

6|Page
Anaconda Distributor Installation.
link: https://www.anaconda.com/products/distribution#Downloads

Step 1) Click on the blue download link that says '64-Bit Graphical Installer' under the
Windows Logo:

Step 2) Locate it by clicking on the ⊞ Start Button and type ‘File Explorer’. Launch File
Explorer:

7|Page
Step 3) On the left side of the File Explorer window, locate and click on Downloads. Double-
click on the downloaded 'Anaconda3-2022.10-Windows-x86_64.exe' file:

Step 4) Then installer launches, step through the installation process. First click Next >.

8|Page
Step 5) Accept the License Agreement by clicking I Agree.

Step 6) Install for 'Just Me' by clicking Next >.

9|Page
Step 7) Accept the default installation location by clicking Next >.

Step 8) Ensure only the bottom checkbox for 'Register Anaconda3 as my default Python 3.x'
is checked and then click Install.

10 | P a g e
Step 9) The installation will proceed. This will take some time to complete.

Step 10) Once the installation completes, click Next >.

11 | P a g e
Step 11) Click Next > to skip through the Data Spell advertisement.

Step 12) Optionally turn off the checkboxes for showing the Tutorial and Getting Started
websites, then click Finish to exit the installation:

12 | P a g e
Step 13) The Anaconda installer will create an icon in the ⊞ Start Menu. To locate it:

Step 14) Anaconda Navigator will launch.:

Anaconda Interface

13 | P a g e
Spyder Interface:

Jupiter Notebook Interface:

14 | P a g e
Pycharm IDE Installation

Step 1) To download PyCharm visit the website


https://www.jetbrains.com/pycharm/download/ and Click the “DOWNLOAD”
Link under the Community Section.

Step 2) Run the exe for install PyCharm. The setup wizard should have started. Click “Next”.

15 | P a g e
Step 3) On the next screen, Change the installation path if required. Click “Next”.

Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.

16 | P a g e
Step 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.

Step 6) Wait for the installation to finish.

17 | P a g e
Step 7) After installation finished, you should receive a message screen that PyCharm is
installed. If you want to go ahead and run it, click the “Run PyCharm Community Edition” box
first and click “Finish”.

Step 8) After you click on “Finish,” the Following screen will appear.

18 | P a g e
Pycharm IDE Interface window

19 | P a g e
Python IDLE Installation

Step 1) To download and install Python, visit the official website of Python
https://www.python.org/downloads/ and choose your version. We have chosen Python version
3.6.3

Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install
Now.

20 | P a g e
Step 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click
on “Close”.

21 | P a g e
Python.org Interface

Conclusion:
Anaconda is a widely used distribution platform for Python and other data science-related
packages. It provides a comprehensive package manager making it convenient for developers
and data scientists to manage their Python projects efficiently. PyCharm is known for its user-
friendly interface and excellent productivity tools, making it a preferred choice for many
Python developers. Python IDLE, which stands for Integrated Development and Learning
Environment, is a basic Python IDE that comes bundled with the standard Python installation.
It provides a simple and lightweight environment for writing, executing, and experimenting
with Python code.
References:
Official website: https://www.anaconda.com/

Anaconda Distribution: https://www.anaconda.com/products/individual

Official website: https://www.jetbrains.com/pycharm/

Official website (Python.org): https://www.python.org/

Python IDLE Documentation: https://docs.python.org/3/library/idle.html

22 | P a g e
Practical No: 2

Title: To learn python code using Arithmetic operators.

Aim: To write python code for using different Arithmetic operators.

Programs:

1. To write python code to Conversion of temperature From Celcius to Fahrenheit.


2. Learn different operators and write python code using (+, -, /, *)
3. Find out area and perimeter od different given geometric shape using python.

23 | P a g e
Practical No: 2.1

Title: To learn python code to Conversion of temperature From Celcius to Fahrenheit.

Aim: To write python code to Conversion of temperature From Celcius to Fahrenheit.

Objective: 1) To write python code to Conversion of temperature From Celcius to Fahrenheit.

Theory:
Here in the program of conversion of temperature. He have used two arithmetic operators called
addition & multiplication.
Celsius
Celsius is a temperature measurement unit that is also known as centigrade. It is an SIderived unit
that is used by the majority of countries throughout the world. It is named after the Swedish
astronomer Anders Celsius.
Fahrenheit
Fahrenheit is a temperature scale named after the Polish-born German physicist Daniel Gabriel
Fahrenheit, and it uses degrees Fahrenheit as a temperature unit.

Algorithm:

Step 1: Start
Step 2: Read the value of temperature to be Converted from user.
Step 3: Assign the value to a variable, Say Cen
Step 4: f = 9/5* cen +32
Step 5: Display f
Step 6: Stop

24 | P a g e
Program:
cen=float(input("Enter the temperature in degree centigrade"))f=9/5*cen+32
print("Temp in degree Centigrade is",cen);print("Temp in degree

farhenheit is",f)

Output:

Enter the temperature in degree centigrade 80


Temp in degree Centigrade is 80.0
Temp in degree farhenheit is 176.0
25 | P a g e
Practical No: 2.2

Title: To learn python code using Arithmetic operators.

Aim: To write python code for using different Arithmetic operators

Objectives: Learn different operators and write python code using (+, -, /, *)

Theory:
Arithmetic operators: An arithmetic operator is an operator that performs mathamatical operation
Addition Subtraction, multiplication, division. modulo, Exponentiation. this is the arithematic
Operations
This section explains the prototypes (syntax) and semantics of all the arithmetic operators in
Python, using its three numeric types: int, float and complex. Some are familiar operators from
mathematics, but others are common only in computer programming. The end of this section
discusses how Python's arithmetic operators apply to bool values and how Python interprets
operands of mixed types (e.g., 3 + 5.0)

i) Addition [+] Adds one operand to the other


ii) Subtraction [-] Subtracts the value. Multiplies one operand by other
iii) Multiplication [*] Multiplication one operand by the second.
iv] Division [/] Divides the first operand by the Second.
v) Exponentiation [**] let you refer to a numberin terms of a base value f an
exponent
vi) Floor division returning a result that is the standard arithmetic quotient of its
operands

26 | P a g e
1) Addition

The + operator in Python can be used in both the binary and unary form. The binary form
means add, returning a result that is the standard arithmetic sum of its operands. The unary
form means identity, returning the same value as its operand.

Algorithm:
Step 1: Start
Step 2: declare variables num 1, num 2
Step 3: reads values num 1 & num 2
Step 4: Sum = num 1 +num 2
Step 5: display sum
Step 6: Stop.

27 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a+b #Addition operator
print("Addition of x and y",z)

Output:

Enter the first number:5


Enter the Second number:4
Addition of x and y: 9

28 | P a g e
2) Substactions

The - operator in Python can be used in both the binary and unary form. The binary form means
subtract, returning a result that is the standard arithmetic difference of its operands: left operand
minus right operand. The unary form means negate, returning the negated value as its operand:
zero to zero, positive to negative, and negative to positive.

Algorithm.
Step 1: Start
Step 2: declare variables num 1 & num 2
Step 3: Reads values num 1 & num 2
Step 4: Sub = num 1- num 2
Step 5: display Subtraction
Step 6: Stop

29 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a-b #Subsraction operator
print("Subtraction of x and y",z)

Output:

Enter the first number:5


Enter the Second number:8
Subtraction of x and y -3

30 | P a g e
3) Multiplication

The * operator in Python can be used only in the binary form, which means multiplication,
returning a result that is the standard arithmetic product of its operands.

Algorithm
Step 1: Start
Step 2: declare variables num 1,num 2
Step 3: reads values num1 & num 2
Step 4: Mul = num 1 * num 2
Step 5: display Mul
Step 6: Stop

31 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a*b #Multiplication operator
print("Multiplication of x and y",z)

Output:

Enter the first number:5 Enter the


Second number:4 Multiplication of
x and y 20

32 | P a g e
4) Division

The / operator (slash) in Python can be used only in the binary form, which means division,
returning a result that is the standard arithmetic quotient of its operands: left operand divided by
right operand.

Algorithm:
Step 1: Start
Step 2 declare variables num 1 + num 2
Step 3: reads value num 1 & num 2
Step 4: Division = num1/num 2
Step 5: display division
Step 6: Stop.

33 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a/b #Division operator
print("Division of x and y",z)

Output:

Enter the first number:5


Enter the Second number:8
Division of x and y : 0.625

34 | P a g e
5) Exponentiation

Python has several exponential arithmetic operators, such as double-stars ()**. This operator has
two operands, a base and an exponent. It calculates the value base to the power of the exponent
(e.g., base exponent) and evaluates expressions such as 3 ** 2 = 9.

Algorithm
Step 1: Start
Step 2: declare variables num 1 , num 2
Step 3: reads values num 1 & num 2
Step 4: not exponentiation. = num 1 ** num 2
Step 5: display Exponentiation.
Step 6: Stop

35 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a**b #Exponent operator
print("Exponent of x and y",z))

Output:

Enter the first number:5 Enter

the Second number:4Exponent

of x and y 625

36 | P a g e
6) Floor division

The // operator (double slash) in Python can be used only in the binary form, which also means
division, but returning an integral result of the standard arithmetic quotient of its operands: left
operand divided by right operand.

Algorithm
Step 1: Start
Step 2: declare variables num1, num2
Step 3: read value num 1, num 2
Step 4: Floor division = num1 /| num 2
Step 5: display Floor division.
Step 6: Stop

37 | P a g e
Program:
a=int(input("Enter the first number:"))b=int(input("Enter
the Second number:"))z=a//b #Floor Division operator
print("Floor Division of x and y",z)

Output:

Enter the first number:5

Enter the Second number:6

Floor Division of x and y 0

38 | P a g e
Practical No: 2.3

Title: To learn python code of area and perimeter of geometric shape.

Aim: To write python code of area and perimeter of given geometric shapes.

Objectives: Find out area and perimeter od different given geometric shape using python.

Theory:

1. Area and perimeter of rectangle.

Here we have to find out area perimeter. Of the rectangle using python programming
Here we have to input the length and width for the area & perimeter.

 Area of Rectangle.

Area of Rectangle is the region occupied by a rectangle within its four sides or
boundaries the are of a rectangle depends. on its Sides Basically, the formula for
area is equal to the product of length & width of the rectangle.

The area of rectangle is given by = length *width

 Perimeter of Rectangle

The perimeter of a rectangle is the total distance covered by its boundaries or the
sides. Since there are four sides of a rectangle, thus the perimeter of the rectangle.
sides. will be the sum of all four sides

Perimeter of Rectangle = 2* (length + width)

39 | P a g e
Algorithm:
Step 1: Start
Step 2: Declare length and width of rectangle
Step 3: Read length & width of rectangle length width.
Step 4: Area = length *width
Step 5: Perimeter = 2* (length + width)
Step 6: Display area of r rectangle 'area'
Step 7: Display perimeter of rectangle 'perimeter
Step 8: Stop

40 | P a g e
Program: length=int(input("length :"))
width=int(input("Width :"))
area=length*width
perimeter=2*(length+width) print("Area of
Reactangle:",area)
print("Perimeter of Reactangle:",perimeter)

Output:

length :14
Width :12
Area of Reactangle: 168

Perimeter of Reactangle: 52

41 | P a g e
2. Area & perimeter of circle.

Here we have to find out area perimeter. Of the circle using python programming
Here we have to input the radius for the area & perimeter.

 Area of circle
Area of circle is given by the area of a circle formula which is made by using a
specific relationship both radius of a circle fits area.

Area of circle = 3.14 * r *r

 Perimeter of circle
the perimeter of a circle formula has 3 components 2 constants + 1 variable which
is the radius of the circle.

Perimeter of circle = 2*3.14*r

Algorithm:-
Step 1: Start
Step 2: Declear radius of circle 'y'
Step 3: Read radius 'r' of circle
Step 4: Area = 3.14 * r *r
Step 5: Perimeter (2*3.14*r)
Step 6: Display area of circle 'area' Display perimeter of circle 'perimeter'
Step 7: Stop

42 | P a g e
Program:
PI= 3.14
r=float(input("Enter radius of the circle:"))area=(PI*r*r)
perimeter=(2*PI*r)
print("The area of circle is:",area) print("The perimeter of
circle:",perimeter

43 | P a g e
Output:

Enter radius of the circle:14The area


of circle is: 615.44
The perimeter of circle: 87.92
Area of Reactangle: 168
Perimeter of Reactangle: 52

44 | P a g e
3. Area of and perimeter of square

To write the program in python' to Find area f perimeter of the Square to Find the area +
perimeter we have to Input the length of the Square

 Area of Square:

Area of square is defined as the number of square units needed to fill a Square In
general, the area is defined as the region. occupied inside the boundary of a Flat
object the measurement is done in Square units, with the standard unit being Square
meters (m²).

The Area of Square = Side*side

 Perimeter of square:

The perimeter of a Square is the distance. covered by its four sides perimeter
surrounds or outlines the shape in a two dimensional plane since, all the sides of a
square are equal, therefore, the perimeter of Square will be 4 times its side ie 4x
Side. It is measured in units, such as m, cm, in, ft etc

Perimeter of square = 4 * Side

Algorithm:-
Step 1: Start
Step 2: Declear side of squar
Step 3: Read value of side
Step 4: Area: Side*side
Step 5: perimeter = 4*side
Step 6: Display area of square
Step 7: Display are perimeter of square
Step 8: Stop

45 | P a g e
Program:
side=int(input("Enter the side of a Square:"))

area=side*side #formula for Area of square


perimeter=4*side #formula for Perimeter of square
print("Area os square:\n",area)
print("perimeter of Square:\n",perimeter)
Output:

Enter the side of a Square:14

Area of square: 196

perimeter of Square: 56

46 | P a g e
CONCLUSION

Arithmetic operators are fundamental mathematical operations used to perform calculations on


numerical values. The main arithmetic operators are addition (+), subtraction (-), multiplication
(*), division (/), and modulus (%). Here's a brief summary of the conclusions regarding these
operators:

These arithmetic operators are essential in performing mathematical calculations and are widely
used in programming languages and everyday calculations. They allow us to manipulate numerical
values and perform various computations efficiently.

REFERENCE

1. MDN Web Docs - Arithmetic Operators:

 Link:https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

 Description: MDN Web Docs is a comprehensive resource for web developers.


Their page on arithmetic operators specifically covers JavaScript, explaining the
usage and behavior of operators like addition, subtraction, multiplication, division,
and modulus.

2. Tutorialspoint - Arithmetic Operators:

 Link: https://www.tutorialspoint.com/cprogramming/c_arithmetic_operators.htm

 Description: Tutorialspoint offers tutorials and references for various programming


languages.

3. Python Documentation - Numeric Types and Arithmetic Operations:

 Link:https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-
complex

 Description: The official Python documentation provides detailed information on


arithmetic operators in Python
47 | P a g e
Practical No: 3

Title: To learn python code using conditions statements if-else construct’s and while & for loop.

Aim: To write python code to preforms programs of statements if-else construct’s and while & for loop.
Programs:
3.1 To learn python code to Check eligibility of voter using if else.
3.2 To learn python code to find the largest number of 3 numbers using nested if.
3.3 To learn python code to write a program using if-elif-else to find out grade of
student whenprovided with percentage of mark.

3.4 To learn python code to write a program to add 1st 100 numbers using while.

3.5 To learn python code to write a program using while loop to separate digit from a given number
and addthem to print result.

3.6To learn python code to Write a program using while to find out factorial number.
Theory:

Conditional statements are an essential part of programming in Python. They allow you to make
decisions based on the values of variables or the result of comparisons.

If :- The condition can be any expression that evaluates to a Boolean value (True or False). If the
condition is True, the code block indented below the if statement will be executed. If the condition is
False, the code block will be skipped.

Syntax:- ifcondition:
# code to execute if condition is true

If-else:- f the condition is True, the code block indented below the if statement will be executed,
and thecode block indented below the else statement will be skipped.
If the condition is False, the code block indented below the else statement will be executed, and the
codeblock indented below the if statement will be skipped.

Syntax:-
if
condition:
# code to execute if condition is true
else: # code to execute if condition is
false

48 | P a g e
Elif:- The elif statement allows you to check multiple conditions in sequence, and execute
different codeblocks depending on which condition is true.

Syntax:- if
condition
1:
# code to execute if condition1 is true
elifcondition2:
# code to execute if condition1 is false and condition2 is true
elifcondition3:
# code to execute if condition1 and condition2 are false, and condition3 is
true else: # code to execute if all conditions are false

Loops:- Loops are important in Python or in any other programming language as they help you to
execute ablock of code repeatedly. You will often come face to face with situations where you
would need to use a piece of code over and over but you don't want to write the same line of code
multiple times.

While:- while loop is a programming concept that, when it's implemented, executes a piece of code
over andover again while a given condition still holds true.

Syntax:-

#While(condition

):
Statement of
body Inc/dec

For:- A for loop is a programming concept that, when it's implemented, executes a piece of code
over andover again "for" a certain number of times, based on a sequence.

Syntax:-

# for(condition)
Statement of body

49 | P a g e
Practical No: 3.1

Title: To learn python code to Check eligibility of voter using if else.

Aim: To write python code to Check eligibility of voter using if else.

Programs: 1) To write python code to Check eligibility of voter using if else.

Theory:
The if-else statement is used to execute both the true part and the false part of a given condition. If
the condition is true, the if block code is executed and if the condition is false, the else block code is
executed.

Syntax :
if ( condition ) :
// body of the statements will execute if the condition is true
else :
// body of the statements will execute if the condition is false

This program is a simple Python script that prompts the user to enter their name and age, and then
checks if the entered age is greater than or equal to 18. If the age is greater than or equal to 18, the
program prints a message stating that the person is eligible to vote, along with their name and age.
If the age is less than 18, the program prints a message stating that the person is not eligible to vote,
along with their name and age.

Algorithm:

Step 1: Start
Step 2: Read the age by the user .
Step 3: Test Situation if age >= 18 then go to step 4 otherwise go to step 5
Step 4: Display " person is eligible for the vote"
Step 5: display "person is not eligible for a vote "
Step 6:End the algorithm

50 | P a g e
Flow chart:

Program:
age = int(input("Enter age : "))

if age >= 18:


print("Eligible for Voting!")
else:
print("Not Eligible for Voting!")

Output:
Enter age : 20
Eligible for Voting!

51 | P a g e
Practical No: 3.2

Title: To learn python code to find the largest number of 3 numbers using nested if.

Aim: To write python code to find the largest number of 3 numbers using nested if.

Objectives: Learn to implant the program to to find the largest number of 3 numbers using nested
if.

Theory:

Given three integers as inputs the objective is to find the greatest among them. In order to do so we
check and compare the three integer inputs with each other and which ever is the greatest we print
that number. Here are some methods to solve the above problem.

Using Nested if-else Statements


In this method we use if-else statements within one another to find the Largest Number among the
three integer inputs.
Working
For integer inputs number1, number2 and number3
 Initialize the required variables.
 Using nested if-else check if the numbers are greater than max and change max if true.
 Print max variable.

Algorithm:

STEP 1: START

STEP 2: Declare three variables X,Y,Z.

STEP 3: If X>Y&X>Z print X is the GREATEST.

STEP 4: Otherwise if Y>Z&Y>X print Y is the GREATEST.STEP 5:

Otherwise print Z is GREATEST.

STEP 6: STOP
52 | P a g e
Flowchart :

53 | P a g e
Program:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output:

Enter the first number:5


Enter the Second number:4
Enter the Third number:6
The largest number is:6

54 | P a g e
Practical No: 3.3

Title: To learn python code to write a program using if-elif-else to find out grade of student when
provided with percentage of mark.

Aim: To write a program using if-elif-else to find out grade of student when provided with
percentage of mark.

Objectives: write a program using if-elif-else to find out grade of student when provided with
percentage of mark.

Theory:

Here we are going to write python program to find grade of a student based on the marks obtained
by student. This code will use decision making statement if-elif-else concept in python.
In computer programming, we use the if statement to run a block code only when a certain
condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.

if the percentage is above 90, assign grade A.


if the percentage is above 75, assign grade B.
if the percentage is above 65, assign grade C.

The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, then we use the
if...elif...else statement.

The syntax of the if...elif...else statement is:


if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Here,
If condition1 evaluates to true, code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, code block 2 is executed.
If condition2 is false, code block 3 is executed.

55 | P a g e
Algorithm:

Step 1 : start
Step 2 : read marks or Percentage
Step 3 : if marks >= 80 then grade =A.
Step 4 : if marks >= 60 and marks <=80 then grade = B.
Step 5 : if marks >=40 and marks <=60 then grade = C .
Step 6 : display failed
Step 7 : display grade.
Step 8 : stop.

Flowchart :

56 | P a g e
57 | P a g e
Program:
marks = float(input("Enter your marks in Computer Science: "))

if marks > 90:


print("Grade: O")
elif marks >= 80 and marks < 90:
print("Grade: A+")
elif marks >= 70 and marks < 80:
print("Grade: A")
elif marks >= 60 and marks < 70:
print("Grade: B+")
elif marks >= 50 and marks < 60:
print("Grade: B")
elif marks >= 40 and marks < 50:
print("Grade: C")
else:
print("Grade: F")

Output:

Enter your marks in Computer Science: 78


Grade: A

58 | P a g e
Practical No: 3.4

Title: To learn python code to write a program to add 1st 100 numbers using while.

Aim: To write a program to add 1st 100 numbers using while.

Objectives: write a program to add 1st 100 numbers using while.

Theory:

While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance.

Statements represent all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses indentation
as its method of grouping statements. When a while loop is executed, expr is first evaluated in a
Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is
still true then the body is executed again and this continues until the expression becomes false.
The while loop in Python is used to iterate over a block of code as long as the truth expression
(condition) is true.
In the given example, we have used the if..else statement in combination with a while loop to
calculate the sum of n numbers. First, we have taken a number input from the user and stored it in a
variable num. Initially, the sum is initialized to 0. The while loop is then used to iterate until
the num equals zero. In every iteration of the loop, we have added the num to the sum, and the
value of the num is decreased by 1.

59 | P a g e
Algorithm:

Step 1:Start
Get an input from the user.
Step 2: Get an input from the user.
Step 3: Check whether the given input is greater than zero or not
Step 4: If the input is greater than zero, then add the numbers using a while loop
Step 5:End the program.

Flowchart :

60 | P a g e
Program:
num = int(input("Enter a number: "))
sum = 0

while(num > 0):


sum += num
num -= 1
print("The result is", sum)

Output:

Enter a number: 100


The result is 5050

61 | P a g e
Practical No: 3.5

Title: To learn python code to write a program using while loop to separate digit from a given
number and add them to print result.

Aim: To Write a program using while loop to separate digit from a given number and add them to
print result.

Objectives: Write a program using while loop to separate digit from a given number and add themto
print result.

Theory:

Given a number as an input the objective is to calculate the sum of the digits of the number. We
first break down the number into digits and then add all the digits to the sum variable. We use the
following operators to break down the string,

Modulo operator %: We use this operator to extract the digits from the number.
Divide operator /: We use this operator to shorten the number after the digit has been extracted.
We use the above-mentioned operators to find the sum of the digits of the number. Here are some of
the methods to solve the above-mentioned problem.

This program allows the user to enter any positive integer, and then that value is assigned to a
variable Number. Next, Condition in the Python While Loop makes sure that the given number is
greater than 0 (Means Positive integer and greater than 0).

62 | P a g e
Algorithm:

Step 1: Start

Step 2: Read num as integer

Step 3: while (num != 0)

begin

dig =num%10;

sum= sum + dig;

num= num/10;

end

Step 4: Print sum

Step 5: Stop

63 | P a g e
Flowchart :

64 | P a g e
Program:
num = int(input("Enter a number: "))
sum = 0

while num! =0:


digit = int(num%10)
sum + = digit
num = num/10

print(“Summation of given number ”,sum)

Output:

Enter a number: 12345


Summation of given number: 15

65 | P a g e
Practical No: 3.6

Title: To learn python code to Write a program using while to find out factorial number.

Aim: To Write a program using while to find out factorial number.

Objectives: Write a program using while to find out factorial number

Theory:
Factorial of a Number can be calculated in many ways. Some of them are by using a for loop, or
using a recursion function or a while loop.

In the following Python Factorial Examples, we will find factorial of a given whole number, using
the above said procedures.
In mathematics, the factorial is the product of all positive whole numbers less than or equal to a
target number.

The factorial is denoted with an exclamation mark.

For example, let’s calculate the factorial of 5:


5! = 5 x 4 x 3 x 2 x 1 = 120
Factorial is a fundamental concept in mathematics and computer science. A factorial program in
Python calculates the factorial of a given number. In this article, we will understand what is a
factorial in python, different approaches of finding factorial along with code and we will also look
at some applications of factorial in Python.

Algorithm:

Step 1: Start program

Step 2 : Ask the user to enter an integer to find the factorial

Step 3 : Read the integer and assign it to a variable

Step 4 : From the value of the integer up to 1, multiply each digit and update the final value

Step 5: The final value at the end of all the multiplication till 1 is the factorial

Step 6:End program

66 | P a g e
Flowchart :

67 | P a g e
Program:
num = int(input("Enter a number: "))

fac = 1
i=1

while i <= num:


fac = fac * i
i=i+1

print("factorial of num is: ", fac)

Output:

Enter a number: 5
factorial of num is : 15

Conclusion:
program determines whether the user is eligible or not. This feature can be particularly useful in
applications that require users to be of a certain age, such as voting, driving, or accessing age-
restricted content.
Secondly, the program performs grade checking. By evaluating the user's input grade against
predefined criteria, it determines whether the grade is passing or failing. This functionality can be
valuable in educational settings or when grading systems are required for specific tasks or
evaluations. The program allows for customization of the grading criteria, making it adaptable to
different grading scales and requirements.
program ensures accurate factorial calculations and provides the results promptly.
Overall, the Python program we have developed incorporates essential functionalities that can be
applied in different contexts. Whether it's determining eligibility based on age, performing grade
checks, or calculating factorials, this program showcases the flexibility and versatility of Python as
a programming language.

References:
Python math module - Official documentation for the math module in Python.
Factorial - Wikipedia article explaining the concept of factorial.
Voting age - Wikipedia article discussing the minimum voting age in different countries.
Grading systems - Wikipedia article explaining different grading systems used in education.

68 | P a g e
Practical No: 4

Title: To Learn Python Programs using Strings .

Aim: To write python code to basic string operations.

Programs: 1) To write python code to basic string operations.


1. String concanteation. 2.String Appending. 3.String Indexing. 4.String Slicing
2) To learn python code to carryout different methods on string.

Theory:
String is collection of alphabets ,words or other charcters . It is one of the primitive
data structure and are the building blocks for data manipulation. python has a built_in
string class named str . python Strings are immutable which means they cannot be
changed after they are created.
Like many other popular programming languages strings in python are arrays of bytes
representing Unicode characters.
However, python does not have a character data type a single character is simply a string
with a length of square brackets can be used to access elements of the strings.

69 | P a g e
Practical No: 4.1

Title: To Learn Python Programs using Strings .

Aim: To write python code to basic string operations.

Objectives: 1) To write python code to basic string operations.


1.String concatenation. 2.String Appending. 3.String Indexing. 4.String Slicing

Theory:
The python string data type is made up of one or more individual characters, where
a character could be a letter , digit, whitespace or any other symbol. Python strings are
"immutable" which means they cannot be changed after they are created (Java strings also
use this immutable style). Since strings can't be changed, we construct *new* stringsas we
go to represent computed values. Strings in python are surrounded by either single
quotation marks, or double quotation marks. 'hello' is the same as "hello".
Syntax:
str=”PVPIT”
Like many other popular programming languages strings in python are arrays of bytes
representing Unicode characters.
However, python does not have a character data type a single character is simply a string
with a length of square brackets can be used to access elements of the strings.

Algorithm:
Step 1: Start
Step 2: Read the input string.
Step 3: Display the string.
Step 4:End the algorithm

70 | P a g e
Flow chart:

Start

Enter the string

Display the result

Stop

Program:
str1=’vishvaja’
str1=”vishvaja”
str1=”’vishvaja”’
print(str1)

Output:

Vishvaja

71 | P a g e
OPERATIONS PERFORMED ON STRINGS:-

1) String Concatenation:
Like number , you can also add two strings in python. The process of
combining two string is called concatenation. Two string whether created using
single or double quotes are concatenated with a same way. We can use’+’
operator to add two strings. Syntax:
str1=”xyz”
str2=”pqr”
print(str1+str2)
2) String Appending:
Append means to add something at the end of string. In python you can add one
string at the end of another string using ‘+=’ operator.
String in python are immutable objects. i.e we can not modify the already existing
string but can add new string to it. It is very easy to append or concatenate strings in
python. Syntax:
str=”Hello”
str+=”World”
print(str)

3) String Indexing:
Individual character in a string are accessed using the the subscript([]) operator.
The expression in brackets is called an index. The index specifies a member of an
ordered set and in this case is specifies the character we want to access from the
given set of character in the string.
The index of the first character is n and that os last character is n-1 when he
is the number of character in the string. If you try to exceed the bounds(below 0
or above n-1) the an errors is raised.
Syntax:
str=”hello”
result=str.index (“e”)
print(result)

4) String Slicing:
You can extract subsets of strings by using the slice operator ([],[:]) you need
specify or the range of index of characters to be extracted. The index of first number
is o and the index of last character is n-1 where n is the number of characters in the
string.
If you want to extract characters starting from the end of the string, then you must
specify the index as a negative number. for e.g the index of the last character is -1.
Syntax:
str= ”hello”
print(str)
print([0])

72 | P a g e
print([-1])

Algorithm:
Step1: Start
Step2: Enter the string.
Step3: Add two strings.
Step4: Append the string.
Step5: Indexing and slicing the string.
Step6: Display the strings.
Step7:End

73 | P a g e
Flowchart:
Start

Take string

Concatenate the string using


str1+str2

Append the string using


result+=str

Indexing the string using


index()

Print the result

Stop

74 | P a g e
Program:

#string concatenation
str1=”welcome to pvpit”
str2=”budhagaon”
print(str1+str2)

O/P:-
Welcome to pvpit budhgaon

#String appending
f_name=”vishvaja”
f_name+=”jadhav”
print(f_name)

O/P:-
vishvaja jadhav

#String indexing
str1=”python”
result=str1.index(‘n’)
print(result)

O/P:-
5

#String slicing
str1=”international airport”
print(str1[2:9])
print(str1[:6])
print(str1[2:])
print(str1[2:-1])

O/P:-
ternati
intern
ternational airport
ternational airpor

75 | P a g e
Practical No. 4.2
Title: To learn python code to carryout different methods on string.

Aim: To write python code to methods performed on string.

Objectives: Learn to different methods of string such as upper(),lower(),split(),etc.

Theory:
Python strings is a built-in type sequence. strings can be handle textual data in
python. python strings are immutable sequences of Unicode points. creating strings is
the simplest and easy to use in python. Python consists following strings methods:
1)upper():-
This method converts a string into upper case.
2) lower():-
This method converts a string into lower case.
3) endswith():-
This methods returns true if the string ends with the specied value.
4) split():-
This method splits the string at the specific operator and returns a list.
5)find():-
This method searches the string for a specified value and return the position or where
it was found.
6) count():-
This method returns the number of times a specified value occurs in a string.
7) isalnum():-
This method returns true if all characters in the string are alpha-numeric.

Algorithm:

STEP 1: Start

STEP 2: Enter the string.

STEP 3:Implement all respective strings methods.

STEP 4: Display the result to the user.

STEP 6: Stop

76 | P a g e
Flowchart:

Start

Take string

Convert upper case with str.upper()

Convert lower case with str.lower()

Find endswith using str.endswith()

Split the string using str.split()

Find particular word using str.find()

Find the count of repeated element


using str.count()

Check given value is alphanumeric


using str.alnum()

Print results

stop

77 | P a g e
Program:

#upper():
str=”pvpit
budhagaon

x=str.upper() print(x)

O/P:-
PVPIT BUDHAGAON

#lower():
str=’BUTTER’
x=str.lower(st
r)print(x)

O/P:-
Butter

#endswith():-
str=’’hello, welcome to pvpit’’
x=str.endswith(‘t’)
print(x)

O/P:-
true

#split():-
str=’’welcome to the
pvpit’’ x=str.split()
print(x)

O/P:-
[‘welcome’,’to’,’the’,’pvpit’]

#find():-
str=’’hello we are human’’
x=str.find(‘we’)
print(x)

O/P:-
7
S
#count():-
str=’’apple’’

78 | P a g e
x=str.count(‘p’)
print(x)
O/P:-
2

#isalnum():-
str=’’company12’
’ x=str.isalnum()
print(x)

O/P:-
True

79 | P a g e
Practical No: 5

Title: Python programs using list operations.

Aim: To learn/ write programs in python using list operations.

Programs:
5.1 Write a program using list to carry out following operations:
1) Create list and print list
2) Repeat a particular element in list
3) Access the elements in the list
4) Loop through list to print its elements

5.2 Write a program using list to carry out following operations:


1) Concatenation of list
2) Merging of list
3) Cloning / copying of list
4) Searching an element in a list
5) Using comparison operator
6) Deleting the list elements

5.3 Use built in functions and list following methods to find out:
1) len, max, min, sum, del, sort and reverse
2) Use following list methods such as append, remove, pop, insert, count and index

5.4 Perform the following operations on a list of names:


1) Create a list of 5 names [Anil,Amol,Aaditya,Avinash,Ajit]
2) Insert a name 'Anuj' before 'Aaditya'
3) Append name 'Abhijit'
4) Delete 'Avinash' from list
5) Replace 'Anil' with 'Anil Kumar'
6) Sort all names in list
7) Print reverse sorted list

80 | P a g e
5.5 Operations on list of numbers
1) Create a list of 5 odd numbers
2) Create list of 5 even numbers
3) Combine two list
4) Add Prime numbers 11,17 & 29 at the begining of combined list
5) Report how many elements are present in list
6) Replace last 3 nos. of list with 100,200,300
7) Delete all members of list
8) Delete the list

Theory:
List is a dynamic datatype available in Python. A list in Python is used to store the sequence of
various types of data. Lists are used to store multiple items in a single variable. A list can be
defined as a collection of values or items of different types. Lists are one of 4 built-in data types
in Python used to store collections of data, all with different qualities and usage. Python lists are
mutable type which implies that we may modify its element after it has been formed. The items
in the list are separated with the comma (,) and enclosed with the square brackets [ ].

Although Python has six data types that may hold sequences, the list is the most popular and
dependable form. The collection of data is stored in a list, a sequence data type. List items can be
of any data type. A list can contain different data types. Similar sequence data formats are Tuples
and String.

Python lists are identical to dynamically scaled arrays that are specified in other languages, such
as Java's ArrayList and C++'s vector. A list is a group of items that are denoted by the symbol [ ]
and subdivided by commas.

List items are ordered, changeable, and allow duplicate values.


 Ordered:-
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change. If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.
 Changeable:-
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
 Allow Duplicates:-
Since lists are indexed, lists can have items with the same value.

81 | P a g e
Experiment No: 5.1

Title: Python programs using list operations like creation, repetition, accessing and looping its
elements.

Aim: To learn programs in python using list operations to create and print list, repeat a particular
element in list,access the elements in list and looping through the list to print its elements.

Objective: To write programs in python using list operations to carry out following operations:
1) Create and print list
2) Repeat a particular element in list
3) Access the elements in list
4) Looping through the list to print its element

Theory:
 Create List:
In any programming language, lists are used to store more than one item in a single variable. In
Python, we can create a list by surrounding all the elements with square brackets [ ] and each
element separated by commas[,]. It can be used to store integer, float, string and more.
 Print List:
To print a list in Python, we can pass the list as argument to print( ) function. The print( )
function converts the list into a string, and prints it to console output.
Program:
#1) Create list & print list
list_PP=["anil","amol","aditya","avinash","ajit",1, 2,3,4,5]
print (list_PP)
Output:
['anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5]

Theory:
 Using ‘*’ Operator:
The * operator can also be used to repeat elements of a list. When we multiply a list with any
number using the * operator, it repeats the elements of the given list. Here, we just have to keep
in mind that to repeat the elements n times, we will have to multiply the list by (n+1).
Program:
#2) Repeat a particular element in list
print (list_PP)
print((list_PP)*3)
Output:
['anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5]
['anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5, 'anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4,
5, 'anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5]

82 | P a g e
Theory:
 Accessing elements:
List items are indexed, the first item has index [0], the second item has index [1] etc.
Negative indexing means start from the end [-1] refers to the last item, [-2] refers to the second
last item etc. List items are indexed and we can access them by referring to the index number.
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Specify negative indexes if we want to start the search from the end of the list.
Program:
#3) Access the elements in the list
print (list_PP)
print(list_PP[0])
print(list_PP[1])
print(list_PP[1:7])
Output:
['anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5]
anil
amol
['amol', 'aditya', 'avinash', 'ajit', 1, 2]

Theory:
 Using a for loop:
Loop Through the Index Numbers. You can also loop through the list items by referring to their
index number. Use the range( ) and len( ) functions to create a suitable iterable.
 Using a while Loop:
You can loop through the list items by using a while loop. Use the len( ) function to determine
the length of the list, then start at 0 and loop your way through the list items by referring to their
indexes.Remember to increase the index by 1 after each iteration.
Program:
#4) Loop through list to print its elements
print (list_PP)
length=(len(list_PP))
for i in range(length):
print(list_PP[i])
Output:
['anil', 'amol', 'aditya', 'avinash', 'ajit', 1, 2, 3, 4, 5]
Anil
amol
aditya
avinash
ajit
1
2
3
4
83 | P a g e
Algorithm:
Step 1 : Start.
Step 2 : Enter the elements in list.
Step 3 : Perform the operations on list.
Step 4 : Print the result.
Step 5 : End.

84 | P a g e
Flow chart:

Start

Input list elements

Carry out following operations:


Read the elements from list
Reapeating element using ‘*’ operator
Accesing elements using indexing
Using of for loop in list

Print :
The elements from list
Repeat the elements n times
New list with the specified index
The elements referring their
index(starts from 0)

Stop

85 | P a g e
Experiment No: 5.2

Title: To learn python programs using list operations like concatenating, merging, cloning,
searching, using comparision operators and deleting the elements of list.

Aim: To write programs in python using list operations to concatenation, merge, clone/copy,
search, using comparision operator and delete elements from list.

Objective: To write a program using list to carry out following operations:


1) Concatenation of list
2) Merging the list
3) Cloning/ copying of the list
4) Searching an element in list
5) Using comparision operator
6) Deleting the list elements

Theory:
 Concatenation of list :
Concatenation of lists is an operation that adds the elements of one list to the end of another list.
The "+" operator can easily join the entire list behind another list and return the new list as the
resulting output.
Program:
list_A=[6,2,5,4,3,1]
list_B=[11,33,22]
#1) Concatenation of list
list_C= list_A + list_B
print (list_C)
Output:
[6, 2, 5, 4, 3, 1, 11, 33, 22]

Theory:
 Merging of list :
It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the
end of the list. It could be done with concatenation method.
Program:
#2) Merging of list
list_C= list_A + list_B
print (list_C)
Output:
[6, 2, 5, 4, 3, 1, 11, 33, 22]

86 | P a g e
Theory:
 Cloning / copying of list:
Cloning or copying a list is simply creating another list that has the same elements as the original
list. Elements in a list can be copied into another list using ‘=’ operator.
Program:
#3) Cloning / copying of list
list_D = list_A
print (list_D)
Output:
[6, 2, 5, 4, 3, 1]

Theory:
 Searching an element :
Python’s “in” operator is a reserved keyword to test membership of the left operand in the
collection defined as the right operand. In fact, Python has two membership operators in and not
in that test whether a value exists in a list.
Program:
#4) Searching an element in a list
print(1 in list_C)
print(6 not in list_C)
Output:
True
False

Theory:
 Comparison operator in list :
Comparison operators, also known as relational operators in Python, compare the values on
either side of them and returns a boolean value. They tell whether a statement is True or False
according to the condition.
Program:
#5) Using comparison operator
print(list_A<list_B)
print(list_C<list_A)
Output:
True
False

Theory:
 Deleting the list element :
This operator takes the item’s index to be removed as the argument and deletes the item at that
index. The operator also supports removing a range of items in the list.

87 | P a g e
Program:
#6) Deleting the list elements
del list_B[0]
print (list_B)
Output:
[33, 22]

Algorithm:
Step 1 : Start.
Step 2 : Input list elements.
Step 3 : Carry out the list operations.
Step 4 : Print the result.
Step 5 : End.

88 | P a g e
Flow chart:

Start

Input list elements

Carry out following operations:


Concatenate list
Merge list
Copy list
Search with membership operator from list
Use of comparison operator in list
Delete the list element

Print :
Concatenated list
Merged list
Copied list
Return ‘True’ or ‘False’ acc. to condition
of membership operator in list
Return ‘True’ or ‘False’ acc. to condition
of comparision operator in list
List without the deleted element

Stop

89 | P a g e
Experiment No: 5.3

Title: : To learn python programs using list operations with built in functions

Aim: To write programs in python using list operations that use built in functions like len, max,
min, sum, del, sort, reverse, append, remove, pop, insert, count and indexing

Objective: To use the built in functions and list following methods to find out:
1) len, max, min, sum, del, sort and reverse
2) Use following list methods such as append, remove, pop, insert, count and index

Theory:
 len :
Returns the number of elements in the list.
 max :
Gets the largest item in a sequence.
 min :
Gets the smallest item in a sequence.
 sum :
The function sum( ) adds all the numbers in list.
 sort :
The sort( ) method sorts the list ascending by default.
 reverse :
The reverse( ) method doesn't take any arguments.The reverse( ) method doesn't return any
value. It updates the existing list. Even the sorted list can be reversed.

Algorithm:
Step 1 : Start.
Step 2 : Enter the elements in list.
Step 3 : Perform the operations on list.
Step 4 : Display the result.
Step 5 : End.

90 | P a g e
Flow chart:

Start

Enter the list elements

Carry out following in-built functions operations:


len, max, min, sum, sort and reverse

Print the result

Stop

91 | P a g e
Program:
#1) Using built in functions like len, max, min, sum, sort and reverse in list
list_A=[6,2,5,4,3,1]
list_B=[11,33,22]

length=(len(list_A))
print ("Length = ", length)

maximum=(max(list_A))
print ("Maximum=", maximum)

minimum=(min(list_A))
print ("Minimum=", minimum)

sumation=(sum(list_A))
print ("Sumation=",sumation)

#Deletion of element
del list_A[0]
print (list_A)

#Sorting of list
list_A.sort()
print (list_A)

# Reversing the list


list_A.reverse()
print (list_A)

Output:
Length = 6
Maximum= 6
Minimum= 1
Sumation= 21
[2, 5, 4, 3, 1]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

92 | P a g e
Theory:
 Append Items :
To add an item to the end of the list, use the append( ) method.
 Remove Specified Item :
The remove( ) method removes the specified item.
 Pop Items :
The pop( ) method removes the specified index.
 Insert Items :
To insert a list item at a specified index, use the insert() method.
The insert( ) method inserts an item at the specified index.
 Count Items :
The count( ) method returns the number of times the specified element appears in the list.
 Index Items :
Python's built-in index() function is a useful tool for finding the index of a specific element in a
sequence. This function takes an argument representing the value to search for and returns the
index of the first occurrence of that value in the sequence.
The method index( ) returns the lowest index in the list where the element searched for appears.
If any element which is not present is searched, it returns a ValueError.

Algorithm:
Step 1 : Start.
Step 2 : Enter the elements in list.
Step 3 : Carry out the operations on list.
Step 4 : Display the result.
Step 5 : End.

93 | P a g e
Flow chart:

Start

Input list elements

Carry out the following list methods:


append, remove, pop, insert, count and index

Display the result

Stop

94 | P a g e
Program:
#2) Use following list methods such as append, remove, pop, insert, count and index
#Appending the list
list_A.append(100)
print(list_A)

# Removing an element in the list


list_A.remove(100)
print (list_A)

# Pop an element in the list


list_A.pop(0)
print (list_A)
#Insert an element in the list
list_A.insert(0,5)
print (list_A)
#Count elements in the list
print(list_A.count(5))

#Index finding in list


Index=list_A.index(5)
print (Index)
Output:
[5, 4, 3, 2, 1, 100]
[5, 4, 3, 2, 1]
[4, 3, 2, 1]
[5, 4, 3, 2, 1]
1
0

95 | P a g e
Experiment No: 5.4

Title: : To learn python programs using list operations like creating, inserting, appending,
deleting, replacing, sorting and reversing the sorted list

Aim: To write programs in python using list operations to create, insert, append, delete, replace,
sort and reverse the sorted list

Objective: To perform a following operations on a list of names:


1) Create a list of 5 names [Anil,Amol,Aaditya,Avinash,Ajit]
2) Insert a name 'Anuj' before 'Aaditya'
3) Append name 'Abhijit'
4) Delete 'Avinash' from list
5) Replace 'Anil' with 'Anil Kumar'
6) Sort all names in list
7) Print reverse sorted list

Program:
#1) Create a list of 5 names
list_names=["Anil","Amol","Aaditya","Avinash","Ajit"]
print(list_names)
Output:
['Anil', 'Amol', 'Aaditya', 'Avinash', 'Ajit']

Theory:
 Insertion of element :
The insert( ) method inserts an element to the list at the specified index.
Program:
#2) Insert a name 'Anuj' before 'Aaditya'
list_names.insert(2,'Anuj')
print(list_names)
Output:
['Anil', 'Amol', 'Anuj', 'Aaditya', 'Avinash', 'Ajit']

Program:
#3) append name 'Abhijit'
list_names.append('Abhijit')
print(list_names)
Output:
['Anil', 'Amol', 'Anuj', 'Aaditya', 'Avinash', 'Ajit', 'Abhijit']

Program:
#4) Delete 'Avinash'
del list_names[4:5]
print(list_names)
96 | P a g e
Output:
['Anil', 'Amol', 'Anuj', 'Aaditya', 'Ajit', 'Abhijit']

Theory:
 Replace elements :
We can access items of the list using indexing. This is the simplest and easiest method to
replace values in a list in python.
Program:
#5) Replace 'Anil' with 'Anil Kumar'
list_names[0]='Anil Kumar'
print(list_names)
Output:
['Anil Kumar', 'Amol', 'Anuj', 'Aaditya', 'Ajit', 'Abhijit']

Program:
#6) Sort all names in list
list_names=sorted(list_names)
print(list_names)
Output:
['Aaditya', 'Abhijit', 'Ajit', 'Amol', 'Anil Kumar', 'Anuj']

Program:
#7) Print reverse sorted list
list_names.reverse()
print(list_names)
Output:
['Anuj', 'Anil Kumar', 'Amol', 'Ajit', 'Abhijit', 'Aaditya']

Algorithm:
Step 1 : Start.
Step 2 : Input the elements in list.
Step 3 : Carry out the operations on list.
Step 4 : Display the result.
Step 5 : End.

97 | P a g e
Flow chart:

Start

Input list elements

Carry out the following operations:


Read the elements from created list
Insertion
Appending an element
Delete element from list
Replacing through indexing
Sorting list
Reversing sorted list

Print :
The elements from list
Inserted element in list
Appended element in list
List without the deleted element
Replace elements from list
Sorted list
Reverse sorted list

Stop

98 | P a g e
Experiment No: 5.5

Title: Python programs using list operations like creating, combining, adding, length, replacing,
deleting elements from list

Aim: To write programs in python using list operations to create, combine, add, check length,
replace, delete the elements from list and delete the whole list

Objective: To perform operations on list of numbers


1) Create a list of 5 odd numbers
2) Create list of 5 even numbers
3) Combine two list
4) Add Prime numbers 11,17 & 29 at the begining of combined list
5) Report how many elements are present in list
6) Replace last 3 nos. of list with 100,200,300
7) Delete all members of list
8) Delete the list

Program:
#1) Create a list of 5 odd numbers
list_odd=[1,3,5,7,9]
print(list_odd)
Output:
[1, 3, 5, 7, 9]

Program:
#2) Create list of 5 even numbers
list_even=[0,2,4,6,8]
print(list_even)
Output:
[0, 2, 4, 6, 8]

Program:
#3) Combine two list
list_no=list_odd+list_even
print(list_no)
Output:
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

Program:
#4) Add Prime numbers 11,17 & 29 at the begining of combined list
list_k=[11,17,29]+list_no
print(list_k)
Output:
[11, 17, 29, 1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

99 | P a g e
Program:
#5) Report how many elements are present in list
b=len(list_k)
print(b)
Output:
13

Program:
#6) Replace last 3 nos. of list with 100,200,300
list_k[-3:]=[100,200,300]
print(list_k)
Output:
[11, 17, 29, 1, 3, 5, 7, 9, 0, 2, 100, 200, 300]

Program:
#7) Delete all members of list
list_k.clear()
print(“\n Cleared List=”,list_k)
Output:
Cleared List=[ ]

Theory:
When we delete the list we won’t be able to see the output. If we try to put the output in program
it will generate the error.
Program:
#8) Delete the list
del list_k

Algorithm:
Step 1 : Start.
Step 2 : Input the elements in list.
Step 3 : Carry out the operations on list.
Step 4 : Print the result.
Step 5 : End.

100 | P a g e
Flow chart:

Start

Input list elements


(Eg : Here two lists
list_odd and

Carry out the following operations:


Read the elements from list(Eg : list_odd)
Read the elements from list(Eg : list_even)
Combine the lists (Here,list_no=list_odd+list_even)
Insert the elements (Here in begining)
Find length of list
Replacing through indexing (Here by negative indexing)
Delete all the elements from list(Here by using ‘clear( )’method)
Delete the list (Here using built-in ‘del’ function)

Print :
The elements from list (Here list_odd)
The elements from list (Here list_even)
Combined list (Here list_no)
Inserted elements list
The length of list
Replaced elements list
Deleted all elements list (Here Cleared list)

Stop

101 | P a g e
Conclusion:
 List is used to store the different data types sequentially. It is ordered, mutable and allows
duplicate values.
 Indexing is important for performing various operations in list.
 There are different methods and in-built fuctions in list for various operations.

Referances:
https://www.geeksforgeeks.org
https://www.tutorialspoint.com
https://www.w3schools.com
https://www.programiz.com
https://www.edureka.co
https://blog.finxter.com
https://flexiple.com

102 | P a g e
Practical no. 6

TITLE: Python programs using tuple.


AIM: To write programs in python using tuple operations.

PROGRAMS:
6.1 – Write a program in python to create tuple, empty tuple, mixed tuple and nested tuple carry out
following operations.
1) Access elements in tuple
2) Use indexing and slicing operations
3) Packing / unpacking

6.2 – Write a program in python to –


1) Convert tuple to list
2) Append the elements
3) Add elements at appropriate position
4) Convert back into tuple
5) Carry out repeat, concatenation, membership operator, len operations.

6.3 – Following tuple is given (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘I’, ‘e’)
Write a python program to
1) Add ‘!’ mark at the end of tuple
2) Convert tuple to string
3) Extract ‘b’ from tuple
4) Find number of occurrences of ‘e’
5) Check ‘g’ exists in tuple
6) Connect tuple to list
7) Delete last 4 character from tuple
8) Print tuple elements using for loop

6.4 – Write a python program to remove empty tuple from the list of tuples.

103 | P a g e
THEORY –
TUPLE-
In Python, a tuple is an ordered, immutable collection of elements. It is one of the built-in data types
in Python. Tuples are similar to lists but with one key difference: tuples cannot be modified once they are
created. This immutability makes tuples useful for situations where you want to store a collection of values
that should not be changed.
Here are some important characteristics and features of tuples in Python:
Syntax: tuple name= (elements)
Tuples are defined by enclosing a comma-separated sequence of values within parentheses.
For example – my tuple= (1,2,3,4,5,6)

Order: Tuples maintain the order of elements. The position of an element in a tuple can be
accessed using indexing.

Immutable: Tuples are immutable, meaning you cannot modify the elements of a tuple after it is created.
Once a tuple is defined, you cannot add, remove, or change elements. However, you can create a new tuple
by concatenating or slicing existing tuples.

Mixed data types: Tuples can contain elements of different data types, such as integers, floats, strings, or
even other tuples.

Accessing elements: Individual elements in a tuple can be accessed using indexing. Indexing starts from 0,
so the first element has an index of 0, the second element has an index of 1, and so on.

Indexing: You can access individual elements in a tuple using their index. Indexing starts at 0 for the first
element, -1 for the last element, -2 for the second-last element, and so on.

Slicing: Slicing allows you to extract a portion of a tuple by specifying a range of indices. The general
syntax for slicing is tuple[start:end:step], where start is the index to start from, end is the index to stop
(exclusive), and step is the step size.

Packing and Unpacking the elements:


In Python, you can pack and unpack tuples. Packing refers to the process of combining multiple values into
a single tuple, while unpacking is the opposite process of extracting values from a tuple into separate
variables.
Packing: Packing is done by enclosing multiple values in parentheses () to create a tuple.
Unpacking: Unpacking allows you to assign the elements of a tuple to individual variables. The number of
variables on the left side of the assignment operator must match the number of elements in the tuple.

104 | P a g e
Converting the tuple into list:
To convert a tuple into a list in Python, you can use the list() function.
Here's an example:
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list)
o/p:- [1, 2, 3, 4, 5]

Appending the tuple:


In Python, tuples are immutable, which means you cannot directly append elements to an existing tuple.
Once a tuple is created, you cannot add or remove elements from it.
However, if you need to add elements to a tuple, you can achieve it by converting the tuple into a list,
appending the elements to the list, and then converting the list back into a tuple.
Here's an example:
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # Convert tuple to list
my_list.append(4) # Append an element to the list
my_tuple = tuple(my_list) # Convert list back to tuple
print(my_tuple)
o/p :- (1, 2, 3, 4)

Concatenate the tuple:


To concatenate or join multiple tuples together, you can use the + operator.
Here's an example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)
o/p- (1, 2, 3, 4, 5, 6)

Membership operators:
In Python, you can use the membership operators to check for the presence of an element in a tuple. The
membership operators are:
in: Returns True if the element is present in the tuple.
not in: Returns True if the element is not present in the tuple.

105 | P a g e
Program 6.1

TITLE- Python program to create various types of tuples and carry out operations on them.

AIM-Write a program in python to create tuple, empty tuple, mixed and nested tuple carry out various
Operations.

OBJECTIVE- 1. To create tuple, empty tuple, mixed tuple, nested tuple and print.
2. To perform following operations on tuple
I. Access elements from tuple
II. Slicing of tuple
III. Indexing in tuple
IV. Packing and Unpacking tuple

ALGORITHM –
STEP 1- Start
STEP 2 – Create tuple, empty tuple, mixed tuple.
STEP 3 – Print all tuples.
STEP 4 – Access and print elements from tuples.
STEP 5 –Slice and print tuples.
STEP 6 –Find index of element in tuple and print index.
STEP 7 –Pack and unpack tuple and print elements.
STEP 8- End

106 | P a g e
FLOW-CHART-

PROGRAM –
#creating a tuple
tpl_a=(0,1,2,6,5,4,8,9,7,3)
print("\ntpl_a=",tpl_a)
#create empty tuple
tpl_b=()
print("tpl_b=",tpl_b)
#create mixed tuple
tpl_c=("PVPIT",11,12,13,14,15,'x','y','z')
print("tpl_c=",tpl_c)
#Accessing the elements from tuple
print(tpl_c[0])
print(tpl_a[1:3])

107 | P a g e
print(tpl_c[-1])
#slicing the tuple
print(tpl_a[::3])
print(tpl_a[1:8])
#indexing in the tuple
index=tpl_a.index(7)
print(index)
#packing and unpacking the tuple
a,b,c,d,e,f,g,h,i,j=tpl_a
print(a)
print(h)

OUTPUT –
tpl_a= (0, 1, 2, 6, 5, 4, 8, 9, 7, 3)
tpl_b= ()
tpl_c= ('PVPIT', 11, 12, 13, 14, 15, 'x', 'y', 'z')
PVPIT
(1, 2)
z
(0, 6, 8, 3)
(1, 2, 6, 5, 4, 8, 9)
8
0
9

108 | P a g e
Program 6.2

TITLE- Python program to convert tuple into list and carry out operation on it.

AIM-Write a python program to convert tuple into list and carry out repeat, concatenation, membership and
len operator.

OBJECTIVE- 1.Convert tuple into list and append the elements


2. Add elements at appropriate position
3. Convert back into tuple
4. Carry out repeat, concatenation, membership operator, len operations on tuple

ALGORITHM-
STEP 1- Start
STEP 2- Create tuple; convert it into list and print
STEP 3- Add element at the appropriate position and print tuple.
STEP 4- Convert list back into tuple.
STEP 5- Print repeated tuple.
STEP 6- Concatenate tuple and print.
STEP 7- Use membership and len operators and print results.

109 | P a g e
FLOW-CHART-

PROGRAM-
#convert tuple to list
tpl_1=('P','Q','R','S','T','U')
list_1= list(tpl_1)
print (type(list_1))
print ('tuple converted into list=',list_1)
# add elements in appropriate position
list_1= list(tpl_1)
list_1 [1]="A"
tpl_1=tuple(list_1)
print("\ntuple after adding element at 1 position=",tpl_1)
110 | P a g e
#convert back to tuple
tpl_1=tuple(list_1)
print(type(tpl_1))
print ('\nlist converted into tuple=',tpl_1)
#Carry out repeat operation
print("\nrepeate tuple 2 times=",tpl_1*2)
#carry out concantination opeartion
tpl_2=(1,2,3)+tpl_1
print('\ntuple after concantination=',tpl_2)
#carry out membership operation
print("2 is in tuple =",2 in tpl_2)
print("d is in tuple =",'d' in tpl_2)
#carry out len operation
print("\nlength of tuple=",len(tpl_2))

OUTPUT –
tuple converted into list= ['P', 'Q', 'R', 'S', 'T', 'U']
tuple after adding element at 1 position= ('P', 'A', 'R', 'S', 'T', 'U')
<class 'tuple'>
list converted into tuple= ('P', 'A', 'R', 'S', 'T', 'U')
repeate tuple 2 times= ('P', 'A', 'R', 'S', 'T', 'U', 'P', 'A', 'R', 'S', 'T', 'U')
tuple after concantination= (1, 2, 3, 'P', 'A', 'R', 'S', 'T', 'U')
2 is in tuple = True
d is in tuple = False
length of tuple= 9

111 | P a g e
Program 6.3

TITLE- Python program to perform various operations on tuple.

AIM- Write a python program to perform various operations on tuple.

OBJECTIVE- 1. Add ‘!’ mark at the end of tuple.


2. Convert tuple to string.
3.Extract ‘b’ from tuple.
4. Find number of occurrences of ‘e’
5. Check ‘g’ exist in tuple or not.
6. Delete last 4 elements from tuple.
7. Print tuple elements using for loop.

ALGORITHM-
STEP 1- Start
STEP 2- Create tuple
STEP 3- Add ‘!’ mark at end of tuple and print
STEP 4- Convert tuple to string and print
STEP 5- Extract ‘b’ from tuple and print
STEP 6- Find no. of occurrence of ‘e’
STEP 7- Check ‘g’ exists in tuple or not.
STEP 8- Convert tuple to list and print.
STEP 9- Delete last 4 elements form tuple and print tuple.
STEP 10- Print tuple elements using for loop.
STEP 10- End

112 | P a g e
FLOW-CHART-

PROGRAM-
# write a python program to do following operatins on given tuple
mytpl=('a','b','c','d','e','f','g','h','i','e')
print(mytpl)
# add ! mark at the end of tuple
mylist=list(mytpl)
mylist.append('!')
mytpl=tuple(mylist)
print(mytpl)

#convert tuple to string


mystring=str(mytpl)
print(type(mystring),mystring)

113 | P a g e
#Extract b from tuple
mylist.remove('b')
print("after extracting b =",mylist)
#find no. of occurrence of 'e'
print ("e occured ",mytpl.count('e'),"times")
#check 'g' exists in tuple
print ("g is present in tuple-",'g'in mytpl)
#convert tuple to list
mylist=list(mytpl)
print(type(mylist),mylist)
#delete last 4 elements from tuple
new_tpl=mytpl[:-4]
print(new_tpl)
#print tuple elements using for loop
for i in new_tpl:
print(i)

OUTPUT-
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e', '!')
<class 'str'> ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e', '!')
after extracting b = ['a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e', '!']
e occured 2 times
g is present in tuple- True
<class 'list'> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e', '!']
('a', 'b', 'c', 'd', 'e', 'f', 'g')
a
b
c
d
e
f
g
114 | P a g e
Program 6.4

TITLE- Delete empty tuple from list of tuples.

AIM-Write python program to delete empty tuple form list of tuples.

OBJECTIVE- Write a python program to delete empty tuple from list of tuples.

ALGORITHM-
STEP 1 - Start
STEP 2 - Initialize the tuple tuple_a with sub-tuples, including some empty ones.
STEP 3 - Display the original tuple_a.
STEP 4 - Filter out the empty sub-tuples from tuple_a using bull function
STEP 5 - Update tuple_a with the filtered result.
STEP 6- Display the updated tuple_a.
STEP 7 - End

FLOWCHART-

START

1. Create tuple list having empty tuple


2. Remove empty tuples using bool function

Print –
1. List of tuples
2. List of tuples after
removing empty tuple

END

115 | P a g e
PROGRAM-

tuple_a = ((1, 2, 3), (), ('a', 'b'), (), ('x', 'y', 'z'), ())
print (tuple_a)
tuple_a = [i for i in tuple_a if bool(i)]
print("tuple list after deleting empty tuple ",tuple_a)

OUTPUT-
((1, 2, 3), (), ('a', 'b'), (), ('x', 'y', 'z'), ())
tuple list after deleting empty tuple [(1, 2, 3), ('a', 'b'), ('x', 'y', 'z')]

116 | P a g e
CONCLUSION –
The above listed programs are implemented in python.
It is learnt that-
 Tuples are immutable, ordered and have integer-based indexing.
 Tuple allow duplicate data to be stored.
 Tuple can have mixed data type.
 Elements can be nested in tuple.

References:

https://www.geeksforgeeks.org
https://www.tutorialspoint.com
https://www.w3schools.com
https://www.programiz.com
https://www.edureka.co
https://blog.finxter.com
https://flexiple.com

117 | P a g e
Practical No: 7

Title: Python programs using Dictionary.

Aim: To learn/ write programs in python using Dictionary.

Programs:
7.1 Write a program using Dictionary to carry out following operations:
1) Create Dictionary data structure and print Dictionary.
2) Create the Dictionary which stores the following data .

Interface IP Address Status


Eth0 1-1-1-1 up
Eth1 2-2-2-2 up
Wlam2 3-3-3-3 down
Wlam3 4-4-4-4 up
7.2 Write a program using Dictionary to carry out following operations:
1) Create Dictionary data structure and print Dictionary.
2) Update the element in Dictionary.
3) Sort elements in the Dictionary.

7.3 Use built in functions and list following methods to find out:
1) Create Dictionary data structure and print Dictionary.
2) Add the element in Dictionary.
3) Set the Value in the Dictionary.
4) sorting the element in Dictionary.
5) Delete the element in Dictionary

Theory:
Dictionary in Python is a collection of keys values, used to store data values. A dictionary in Python is
made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary.
The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict()
function.
Python dictionary are identical to dynamically scaled arrays that are specified in other languages, such as
Java's ArrayList and C++'s vector. A dict is a collection of keys values that are denoted by enclosed in carly
brackets ({}).

Dictionary items are ordered, changeable, and does not allow duplicate values.
• Ordered:-

118 | P a g e
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change. If you add new items to a dict, the new items will be placed at the end of the dict.
Note: There are some dict methods that will change the order, but in general: the order of the items will
not change.
• Changeable:-
The dict is changeable, meaning that we can change, add, and remove items in a dict after it has been
created.
• Does not Allow Duplicates:-
Since dict are indexed, dict can have items with the same value.

When we delete the dict we won’t be able to see the output. If we try to put the output in program it will
generate the error.

1. In any programming language, dictionary are used to store values as a pair of key and value.
Each key is separated from its value by a colon (:) and consective items are separated by commos.
The entire items in a dictionary are enclosed in carly brackets ({}).
1.1 Using ‘=’ Operator:
The = operator can also be used to find elements of a dict. Values in a Python dictionary can be accessed
by placing the key within square brackets next to the dictionary. Values can be written by placing key
within square brackets next to the dictionary and using the assignment operator ( = ). If the key already
exists, the old value will be overwritten.
1.2 Add the elements:
Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by
defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key
values can also be added to an existing Dictionary.

Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key
with the value is added to the Dictionary.

2. Sort the dictionary:


We need sorting of data to reduce the complexity of the data and make queries faster and more efficient.
Therefore sorting is very important when we are dealing with a large amount of data. Create a dictionary and
display its list-keys alphabetically.
Display both the keys and values sorted in alphabetical order by the key.
First, sort the keys alphabetically using key_value.iterkeys() function .
2.1 Set the values in the dictionary:
Values can be written by placing key within square brackets next to the dictionary and using the assignment
operator ( = ). If the key already exists, the old value will be overwritten. Attempting to access a value with
a key that does not exist will cause a KeyError .

3. Add :
Inserting a new index key into the dictionary, then assigning it a particular value.
• Add the new key :
We can add a new key to a dictionary by assigning a value to it. If the key is already present, it overwrites
the value it points to. The key has to be written in subscript notation to the dictionary like this:
Syntax :
my_dictionary[new_key] = new_value

119 | P a g e
Delete :
The clear () method removes all elements from the dictionary.
• Delete :
We can use a del keyword and for loop to remove the multiple keys from the dictionary in Python. First, we
have to initialize the list of keys that we want to remove from the dictionary. Then using the del keyword
we will remove the list of specified keys from the dictionary with the help of iterating.

Sort :
The sort( ) method sorts the dictionary ascending by default
• Sort the items :
Declare a dictionary which is to be sorted.
Declare an empty dictionary where sorted key value pairs are to be added
sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. For each key
in sorted order, add the key and the corresponding value into dic2.
dic2 has all the key-value pairs in sorted order of keys.

120 | P a g e
Experiment No: 7.1

Title: Python programs using Dictionary operations like create, find, access and Add elements.

Aim: To learn programs in python using Dictinary operations to create and print list, Find a particular
element in dictionary, access the elements in dictionary and Add the dict to print its elements.

Objective: To write programs in python using dictionary operations to carry out following operations:
1) Create and print dictionary
2) find a particular element in dictionary

Algorithm:

Step 1 : Start.
Step 2 : Enter the elements in Dictionary.
Step 3 : Perform the operations on Dictionary.
Step 4 : Print the result.
Step 5 : End.

121 | P a g e
Flow chart:

Start

Input Dictionary
elements

Carry out following operations:

Read the elements from dict

Find the elements in the dict

Print :

The elements from dict

New dict with the specified index

find the dict

Stop

122 | P a g e
Program:
#1) Create dict & print dict
dict={ 'ln1':{'interface':'eth0',

'status': 'up', 'ip_address': '1.1.1.1'},

'ln2':{'interface':'eth1',
'up', 'ip_address': '2.2.2.2'},

'ln3':{'interface':'wlan0', 'status':'down', 'ip_address': '3.3.3.3'},

'ln4':{'interface':'wlan1', 'status': 'up', 'ip_address': '4.4.4.4'}

print(dict)

• Output:
{'ln1': {'interface': 'eth0', 'status': 'up', 'ip_address': '1.1.1.1'}, 'ln2': {'interface': 'eth1', 'status': 'up',
'ip_address': '2.2.2.2'}, 'ln3': {'interface': 'wlan0', 'status': 'down', 'ip_address': '3.3.3.3'}, 'ln4': {'interface':
'wlan1', 'status': 'up', 'ip_address': '4.4.4.4'}}

Program:
#2) Find a particular element in dict
# Find the status of given interface

def find_interface_status(interface):

if interface in Dict1:

return Dict1[interface]['status']

else:

return "Interface not found"

interface =input("Enter the interface name:")

status = find_interface_status(interface)

print(f"The status of interface {interface} is: {status}")

Output:
Enter the interface name:eth0

The status of interface eth0 is: up

Program:
#3) Total no of interface
total_interfaces=len(Dict1)

print("total number of interfaces",total_interfaces)

123 | P a g e
Output:
total number of interfaces 4

Program:
#4) Add the new entries to dictionary
Dict1['eth2']={'Ip address':'5.5.5.5','status':'down'}

print(Dict1)

Output:
{'eth0': {'Ip address': '1.1.1.1', 'status': 'up'}, 'eth1': {'Ip address': '2.2.2.2', 'status': 'up'}, 'wln0': {'Ip address':
'3.3.3.3', 'status': 'down'}, 'wln1': {'Ip address': '4.4.4.4', 'status': 'up'}, 'eth2': {'Ip address': '5.5.5.5', 'status':

124 | P a g e
Experiment No: 7.

Title: To learn python programs using Dictionary operations like finding , sorting , & set the values in the
Dictionary .
Aim: To write programs in python using dict operations to find , sort & search the element in the
dictionary.
Objective: To write a program using dictionary to carry out following operations:
1) sorting the dict
2) set the values in the dict
Algorithm:
Step 1 : Start.
Step 2 : Enter the elements in dict.
Step 3 : Perform the operations on dict.
Step 4 : Display the result.
Step 5 : End.

Flow chart:
Start

Input dict elements

Carry out following operations:

find the elements in dict

sort the dict

set the values in dict

Print :

find the particular element in the dict

sort the values in the dict

Stop

125 | P a g e
Program:
#1) Print marks obtained by amol in english & sort the dict by names
marks={

'subu':{'maths':88,'eng':60,'ss':95},

'amol':{'maths':78,'eng':68,'ss':89},

'rahul':{'maths':56,'eng':66,'ss':77}}

print(marks)

# sort the dictionary by name

marks1=sorted(marks.items())

print('Asc.order by key:',marks)

marks2=sorted(marks.items(),reverse=True)

print('Des.order by key:',marks2)

Output:
{'subu': {'maths': 88, 'eng': 60, 'ss': 95}, 'amol': {'maths': 78, 'eng': 68, 'ss': 89}, 'rahul': {'maths': 56, 'eng':
66, 'ss': 77}}

Asc.order by key: {'subu': {'maths': 88, 'eng': 60, 'ss': 95}, 'amol': {'maths': 78, 'eng': 68, 'ss': 89}, 'rahul':
{'maths': 88, 'eng': 66, 'ss': 77}}

Des.order by key: [('subu', {'maths': 88, 'eng': 60, 'ss': 95}), ('rahul', {'maths': 88, 'eng': 66, 'ss': 77}), ('amol',
{'maths': 78, 'eng': 68, 'ss': 89})]

Program:
#2) Set the marks obtained by rahul in maths=88
#udate rahul maths marks

marks['rahul']['maths']=88

print (marks)

Output:
{'subu': {'maths': 88, 'eng': 60, 'ss': 95}, 'amol': {'maths': 78, 'eng': 68, 'ss': 89}, 'rahul': {'maths': 88, 'eng':
66, 'ss': 77}}

126 | P a g e
Experiment No: 7.3

Title: : To learn python programs using dictionary methods.

Aim: To write programs in python using dictionary methods like Add , sort , delete & set values in the
given dictionary.
Objective: To use the following methods in the dictionary:
• Add , Sort , Delete.
Algorithm:
Step 1 : Start.
Step 2 : Input dict elements.
Step 3 : Carry out the dict operations.
Step 4 : Print the result.
Step 5 : End.

Start
Flow chart:

Input dict elements

Carry out following operations:

find the elements in dict

sort the dict

set the values in dic

Print :

find the dict

sort the dict

Stop

127 | P a g e
Program:
portfolio={'accounts':['sbi','10B'],

'shares':['hdfc','icici','tm','tcs'],

'ornaments':['10GM gold','1KG

silver']}

#1) Add key to portfolio called 'mf' with values 'relience','absl'

portfolio['mf']=['reliance','absl']

print(portfolio)

Output:
{'accounts': ['sbi', '10B'], 'shares': ['hdfc', 'icici', 'tm', 'tcs'], 'ornaments': ['10GM gold', '1KG silver'], 'mf':
['reliance', 'absl']}

Program:

# 2) sort the items in the list stored under the 'shares' key

portfolio['accounts']=['ASIS','808']

print(portfolio)

Output:
'accounts': ['ASIS', '808'], 'shares': ['hdfc', 'icici', 'tm', 'tcs'], 'ornaments': ['10GM gold', '1KG silver'], 'mf':
['reliance', 'absl']}

Program:

# 3) Delete the last stored under ‘ornaments’ key

del portfolio['accounts']

print(portfolio)

Output:

{'shares': ['hdfc', 'icici', 'tm', 'tcs'], 'ornaments': ['10GM gold', '1KG silver'], 'mf': ['reliance', 'absl']}

128 | P a g e
Conclusion:

The above listed programs are implemented in python.

It is learn that-

• Dictionary in Python is a collection of keys values, used to store data values.


• Dictionary items are ordered, changeable, and does not allow duplicate values.
• Various operations in dictionary are performed using indexing.
• Various operations in dictionary use different methods for execution .

Referances:
https://www.geeksforgeeks.org
https://www.tutorialspoint.com
https://www.w3schools.com
https://www.programiz.com
https://www.edureka.co
https://blog.finxter.com
https://flexiple.com

129 | P a g e
Practical no. 8

TITLE: Python programs using function.

AIM: To write programs in python using function operations.

PROGRAMS:
8.1) write a python program to find Factorial of given using function.

8.2) Solve using the following series using function.


Sum = 4/1! + 3/3! + 5/5! + 7/7! + ….. Take first 5 terms.

8.3) write a program that defined function to count alphabets, white spaces and numbers from a
given sting. Also measure the length of string after subtracting white space.

8.4) Create array of 10 numbers and reverse it, Write a function to add and subtract the array
element and print the result

 Carry out elementwise multiplication and division also


THEORY –

A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing. As
you already know, Python gives you many built-in functions like print, etc. but you can also create
your own functions. These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.

 Function blocks begin with the keyword def followed by the function name and parentheses
( ).

130 | P a g e
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
 The code block within every function starts with a colon ( : ) and is indented.
 The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.

Syntax:

def functionname( parameters ):


"function_docstring"
function_suite return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.

Example:

The following function takes a string as input parameter and prints it on standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme function –

131 | P a g e
Example:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Output:-
I'm first call to user defined function!
Again second call to the same function

132 | P a g e
Pass by reference vs value

All parameters arguments in the Python language are passed by reference. It means if you change

what a parameter refers to within a function, the change also reflects back in the calling function.

Example:

#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Output:-
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

133 | P a g e
Function Arguments
You can call a function by using the following types of formal arguments:
1) Required arguments
2) Keyword arguments
3) Default arguments
4) Variable-length arguments

1) Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.

Example:
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()

Output:-
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

134 | P a g e
2) Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters. You can also make keyword
calls to the printme function in the following ways –

Example:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")

Output:
My string

135 | P a g e
3) Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it prints
default age if it is not passed –

Example:

#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Output:

Name: miki
Age 50
Name: miki
Age 35

136 | P a g e
4) Variable-length arguments

You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.

An asterisk ∗ is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example –

Example:
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 )
printinfo( 70, 60, 50 )

Output:
Output is:
10
Output is:
70
60
50

137 | P a g e
Practical no. 8.1

TITLE: - Python program to create various types of function and carry out operations on them.

AIM: Write a python program to find Factorial of given using function. .

OBJECTIVE : Find factorial number in python using recursion function

ALGORITHM –

Start 1: Start
Start 2: Factorial (n)
Start 3: number == 1
Start 4: Return = n * factorial(n - 1) / Return = 1
Start 5: Enter a number =
Start 6: Print
Start 7: End

138 | P a g e
Flowchart

Start

Input a number

Defind function
Factorial (n)

No Yes
if n == 0 or
n == 1:

Calculate factorial Return = 1


Number * factorial (n - 1)

Output “The factorial of”


{num} is {result}

Stop

139 | P a g e
PROGRAM
def factorial(n):
if n == 0 or n == 1:
return
1 else:
return n * factorial(n - 1)
num = int(input("Enter a
number: ")) result =
factorial(num)
print(f"The factorial of {num} is {result}.")

OUTPUT :
Enter a number: 5
The factorial of 5 is 120.

140 | P a g e
Practical no. 8.2

TITLE: - Python program to create various types of function and carry out operations on them.

AIM: Write a python program using the series function. .

OBJECTIVE : Solve the following series using function.

Sum = 4/1! + 3/3! + 5/5! + 7/7! + ….. Take first 5 terms.

ALGORITHM –

Start 1: Start
Start 2: 1) Assign 0 to series_sum
2) Assign 11 to denominator
Start 3: For i in range (n)
Start 4: 1) Calculate 2 * i + 1
2) Calculate numerator
3) Add term to series_sum
4) Increment denominator by 20
Start 5: Return series_sum
Start 6: End

141 | P a g e
FLOW-CHART

Start

Input a number of term (n)

Define function to calculate series


Sum of series upto given number

Initialize value of i to 0

Update series sum

No

is i = n

Yes

Result

Stop

142 | P a g e
PROGRAM
def
calculate_series_sum(n)
: sum = 0
denominator =
11 for i in
range(n):
numerator = 2 * i + 1
term = numerator /
denominatorsum += term
denominator +=
20return sum
n=5
series_sum = calculate_series_sum(n)
print(f"The sum of the series is:
{series_sum}")

OUTPUT :
The sum of the series is: 0.483215148340626

143 | P a g e
Practical no. 8.3

TITLE: - Python program to create defined function to count alphabets, white spaces and numbers
from a given sting.

AIM: Write a python program using the defined function to count alphabets, white spaces and
numbers from a given sting. .

OBJECTIVE : Defined function to count alphabets, white spaces and numbers from a given
sting. Also measure the length of string after subtracting white space.

ALGORITHM –

Start 1: Start
Start 2: 1) Define function: count_characters(string)
2) Initialize , alphabet = 0, whitespace = 0 , number = 0 , length = 0
Start 3: for char in string:
Start 4: 1 increment alphabet by 1 , increment whitespace by 1 , increment number by 1
Start 5: Enter a number =
Start 6: Print
Start 7: End

144 | P a g e
FLOW-CHART

Start

Input a string

Define function to count characters

increment alphabet ,
whitespace by, number by 1

No

Calculate
If stringlength

Yes
Display result

Stop

145 | P a g e
PROGRAM
def
count_characters(string)
: alphabet_count = 0
whitespace_count = 0
number_count = 0
length_without_spaces
= 0for char in string:
if char.isalpha():
alphabet_count +=
1
elif char.isspace():
whitespace_count +=
1
elif char.isdigit():
number_count +=
1
length_without_spaces = len(string.replace(" ", ""))
return alphabet_count, whitespace_count, number_count, length_without_spaces
input_string = "Hello world! 123"
alphabets, whitespaces, numbers, length =
count_characters(input_string) print("Alphabets:", alphabets)
print("White spaces:", whitespaces)
print("Numbers:", numbers)
print("Length without spaces:",
length)

146 | P a g e
OUTPUT :
Alphabets: 10
White spaces: 2
Numbers: 3
Length without spaces: 14

147 | P a g e
Practical no. 8.4

TITLE: - Python program to create array of 10 numbers and reverse it.

AIM: Write a python program array of 10 numbers and reverse it, Write a function to add and
subtract the array element and print the result

OBJECTIVE : Create array of 10 numbers and reverse it, Write a function to add and subtract
the array element and print the result

 Carry out elementwise multiplication and division also.

ALGORITHM –
Start 1: Start
Start 2: 1) Define the function reverse_array(arr):
2) Define the function add_array(arr):
3) Define the function subtract_array(arr):
4) Define the function multiply_array(arr):
5) Define the function divide_array(arr):
Start 3: 1) Return the result
2) Create an array numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Start 4: 1) Assign the reversed array of numbers to reversed_numbers
2) Assign the sum of numbers to addition
3) Assign the result of subtracting
4) Assign the product to multiplication
5) Assign the result of dividing to divisionStart 5: Enter a number =
Start 6: Print
Start 7: End

148 | P a g e
FLOW-CHART

Start

Define the function


reverse_array(arr):
add_array(arr):
subtract_array(arr):
multiply_array(arr):

Create an array numbers

Display result

Stop

149 | P a g e
PROGRAM
def
reverse_array(arr)
: return arr[::-1]
def
add_array(arr):
return sum(arr)
def
subtract_array(arr)
: result = arr[0]
for i in range(1,
len(arr)): result -=
arr[i]
return result
def
multiply_array(arr)
: result = 1
for num in arr:
result *=
num
return result
def
divide_array(arr)
: result = arr[0]
for i in range(1, len(arr)):
result /= arr[i] return
result
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

150 | P a g e
reversed_numbers =
reverse_array(numbers) addition_result =
add_array(numbers) subtraction_result =
subtract_array(numbers)
multiplication_result =
multiply_array(numbers) division_result =
divide_array(numbers) print("Original
array:", numbers) print("Reversed array:",
reversed_numbers) print("Addition result:",
addition_result) print("Subtraction result:",
subtraction_result)
print("Multiplication result:",
multiplication_result) print("Division result:",
division_result)

151 | P a g e
OUTPUT :
Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Reversed array: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Addition result: 55
Subtraction result: -53
Multiplication result: 3628800
Division result: 2.7557319223985894e-07

CONCLUSION
The definition of the function object called square is shorter clearer and truer to its mathematical
(conceptual) definition. This course illustrates that creative programming is about constructing
useful abstractions. It is also about exercising your intuition to make you more productive.

REFERENCES

1) https://docs.python.org/3/tutorial/ function.html
2) https://docs.python.org/3/tutorial/ function s.html
3) https://www.geeksforgeeks.org/python- function
4) https://www.geeksforgeeks.org/ python

152 | P a g e
Practical No: 9

Title: To Learn Python Programs For Creating Module and Packages.

Aim: To write python code For Creating Module and Packages.

Programs:
1) To write python code for creating module to find large number out of given three numbers.
2) To learn python code to create package that preforms basic operation of calculator.
Theory:
In Python, modules and packages are essential concepts that help organize and structure code for
better reusability and maintainability. Let's explore the theory related to modules and packages in
Python:
1. Modules:
 A module is a file containing Python definitions, statements, and functions that can
be imported and used in other Python programs.
 Modules allow you to organize related code into separate files, making it easier to
manage and reuse functionality.
 Each module has its own namespace, which serves as a container for its variables,
functions, and classes. This helps avoid naming conflicts between different modules.
 You can create your own modules by writing Python code in a .py file and importing
it into other Python scripts.
 Python provides a wide range of built-in modules that offer various functionalities,
such as math, random, datetime, and more.
2. Packages:
 A package is a way of organizing related modules into a hierarchical directory
structure.
 A package is essentially a directory that contains multiple module files and a special
file called init .py. The init .py file can be empty or can contain
initialization code for the package.
 Packages allow you to group modules that have similar functionalities or belong to
the same project or framework.
 Packages help avoid naming conflicts between modules by providing a unique
namespace for each package.
 Packages enable the use of a hierarchical naming structure, where you can access
modules within a package using dot notation.
 Packages can have sub-packages, allowing for even further organization and division
of functionality.

3. Importing Modules and Packages:


 To use a module or package in your Python code, you need to import it.
 You can import an entire module using the import statement followed by the
module name. For example: import module_name.

153 | P a g e
 After importing a module, you can access its variables, functions, and classes using
dot notation. For example: module_name.function_name().
 If you only need specific items from a module, you can use the from keyword to
import them directly. For example: from module_name import function_name.
 When importing packages, you can use dot notation to access modules within the
package. For example: import package_name.module_name.
 Python provides various import techniques, including aliasing imports, importing all
items from a module, conditional imports, and more, to provide flexibility and
control over the imported items.

154 | P a g e
Practical No: 9.1

Title: To Learn Python Programs for Creating Module and Packages.

Aim: To write python code for creating Module and Packages in python.

Objectives: Creating Module for finding greatest number from given three numbers.

Theory:
1. Open a text editor or an Integrated Development Environment (IDE) of your choice.
2. Create a new Python file with a .py extension. For example, mymodule.py.
3. Define the functions, classes, or variables that you want to include in your module. Write the
code for each component. Here's an example:
Program:
def greet(name):
"""
Prints a greeting message with the provided name.
"""
print("Hello, " + name + "!")

def add(a, b):


"""
Adds two numbers and returns the result.
"""
return a + b

PI = 3.14159

4. Save the file with the module code in a directory of your choice.
5. Your module is now created and ready to be used in other Python scripts.
To use the module in another Python script:
1. Create a new Python file or open an existing one.
2. Import the module using the import statement followed by the name of your module. For
example:
import mymodule
If your module is in a different directory, you can use the sys module to add the directory to

155 | P a g e
the Python path before importing. Here's an example:

import sys
sys.path.append('/path/to/module_directory')
import mymodule

3. Once imported, you can access the functions, classes, or variables defined in your module
using the module name as a prefix. For example:
mymodule.greet("Alice")
result = mymodule.add(2, 3)
print(result)
print(mymodule.PI)
4. Run the script, and it will execute the code using the functions, classes, or variables from
your module.

Algorithm:
1. Start

2. Define a function named "find largest" that takes three parameters: a, b, and c

3. Inside the function:


a. If a is greater than or equal to both b and c, assign a to the variable "largest"
b. Else if b is greater than or equal to both a and c, assign b to the variable "largest"
c. Else, assign c to the variable "largest"
d. Return the value of "largest"

4. End function

5. Call the "find largest" function with three numbers as arguments to get the result

6. Display the result, indicating the largest number among the three

7. Stop

156 | P a g e
Flowchart:

157 | P a g e
Program:

1. Create a new Python file named largest_number.py:


Python Copy code
def find largest(a, b, c):
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

2. Save the file and ensure that it's in the same directory as the script you'll be using to import
the module.

3. Create another Python file where you want to use the module. For example, main.py:
# Import the module
import largest_number

# Get user input


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

# Call the function from the module


result = largest_number.find_largest(num1, num2, num3)

# Display the result


print("The largest number is:", result)

4. Save the main.py file.

5. Run the main.py file, and it will import the largest_number module and call the
find_largest function to determine the largest number among the given three numbers. The
result will be displayed on the console.

Make sure to have both largest_number.py and main.py files in the same directory, and execute
main.py to see the output.

Output:

158 | P a g e
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30

The largest number is: 30

159 | P a g e
Practical No: 9.2

Title: To Learn Python Programs for Creating a package for python to create a basic calculator
functions.

Aim: To write python code for Creating a package for python to create a basic calculator
functions.

Objectives: Creating a package for python to create a basic calculator functions.

Theory:
We organize a large number of files in different folders and subfolders based on some criteria, so
that we can find and manage them easily. In the same way, a package in Python takes the concept of
the modular approach to next logical level. As you know, a module can contain multiple objects,
such as classes, functions, etc. A package can contain one or more relevant modules. Physically, a
package is actually a folder containing one or more module files.
1. Create a new directory for your package: Choose a name for your package (e.g., calculator)
and create a new directory with that name.
2. Create the init .py file: Inside the calculator directory, create a new file named
init .py. This file will initialize the package and allow it to be treated as a package by
Python.
3. Create the calculator module: Inside the calculator directory, create another Python file,
e.g., calculator.py. This file will contain the code for your calculator functions.
4. Define calculator functions: In the calculator.py file, define the functions for basic
mathematical operations such as addition, subtraction, multiplication, and division. Here's
an example implementation:
5. Save the files: Save both the init .py and calculator.py files inside the calculator
directory.
6. Test the package: Create a new Python script in the same directory or any other location and
import the calculator package. Use the calculator functions to perform calculations.
When you run the script, it will perform calculations using the functions from the calculator
package.

160 | P a g e
Algorithm:

1. Start

2. Create a new directory for the package and give it a suitable name (e.g., "calculator")

3. Inside the package directory, create an empty file named " init .py". This file is required to
initialize the package.

4. Create a new Python file inside the package directory, named "calculator.py". This file will
contain the code for calculator functions.

5. Define the calculator functions in the "calculator.py" file:

a. Define a function for addition that takes two numbers, "a" and "b", as parameters and returns
their sum.
b. Define a function for subtraction that takes two numbers, "a" and "b", as parameters and returns
their difference.
c. Define a function for multiplication that takes two numbers, "a" and "b", as parameters and
returns their product.
d. Define a function for division that takes two numbers, "a" (dividend) and "b" (divisor), as
parameters and returns their quotient.

6. Save the files and close them.

7. Test the package:


a. Create a new Python script in the same directory as the package or in any location.
b. Import the "calculator" package by using the package name followed by the module name:
"from calculator import calculator".
c. Use the calculator functions to perform calculations, passing the required arguments.
d. Display the results.

8. Stop

161 | P a g e
Flowchart:

162 | P a g e
Program:
1. Create a new directory for your package: Choose a name for your package (e.g., calculator)
and create a new directory with that name.
2. Create the init .py file: Inside the calculator directory, create a new file named
init .py. This file will initialize the package and allow it to be treated as a package by
Python.
3. Create the calculator module: Inside the calculator directory, create another Python file,
e.g., calculator.py. This file will contain the code for your calculator functions.
4. Define calculator functions: In the calculator.py file, define the functions for basic
mathematical operations such as addition, subtraction, multiplication, and division. Here's an
example implementation:

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


return a / b

5. Save the files: Save both the __init .py and calculator.py files inside the calculator
directory.
6. Test the package: Create a new Python script in the same directory or any other location
and import the calculator package. Use the calculator functions to perform calculations. Here's
an example:

# Import the calculator package


from calculator import calculator

# Use the calculator functions


result = calculator.add(5, 3)
print("Addition result:", result)

result = calculator.subtract(7, 2)
print("Subtraction result:", result)

result = calculator.multiply(4, 6)
print("Multiplication result:", result)

result = calculator.divide(10, 2)
163 | P a g e
print("Division result:", result)

Output:

Addition result: 8
Subtraction result: 5
Multiplication result: 24
Division result: 5

164 | P a g e
Practical No: 9.3

Title: To Learn Python Programs for Creating a module function f1( ),f2( ),f3( ).

Aim: To write python code for Creating a module function f1( ),f2( ),f3( ).
Objectives: Creating a package for python to create a basic calculator functions.

Theory:
1. Create a new Python file and name it something meaningful, like operations.py.
2. Inside the operations.py file, define the f1 function to calculate the factorial of a number:
 Accept a parameter, n, which represents the number for which the factorial will be
calculated.
 Check if n is less than 0. If so, return an error message since factorial is not defined
for negative numbers.
 Check if n is equal to 0. If so, return 1 since the factorial of 0 is defined as 1.
 Initialize a variable, factorial, with a value of 1.
 Use a loop to calculate the factorial of n by multiplying factorial with each number
from 1 to n.
 Return the calculated factorial.
3. Define the f2 function to add the first 100 numbers:
 This function doesn't accept any parameters.
 Use the sum function and the range function to generate a sequence of numbers
from 1 to 100.
 Pass this sequence of numbers to the sum function to calculate their sum.
 Return the sum.
4. Define the f3 function to add the first 50 even numbers:
 This function doesn't accept any parameters.
 Use the sum function and the range function to generate a sequence of even
numbers from 0 to 100.
 Pass this sequence of numbers to the sum function to calculate their sum.
 Return the sum.

165 | P a g e
5. Save the operations.py file.
To use this module, follow these steps:

1. Create a new Python script in the same directory as the operations.py module.
2. Import the operations module using the import statement: import operations.
3. Call the functions from the operations module as needed, providing the required arguments:
 For example, to calculate the factorial of a number, use operations.f1(n), where n is
the number for which you want to calculate the factorial.
 To add the first 100 numbers, use operations.f2().
 To add the first 50 even numbers, use operations.f3().
4. Display the results as desired.

Algorithm:

1. Start

2. Define a function named "f1" that takes a parameter "n":


a. If n is less than 0, return an error message.
b. If n is equal to 0, return 1.
c. Initialize a variable "factorial" with a value of 1.
d. Use a loop to calculate the factorial of n:
i. Initialize a variable "i" with a value of 1.
ii. Repeat the following steps until i reaches n+1:
- Multiply "factorial" by "i" and assign the result to "factorial".
- Increment "i" by 1.
e. Return the value of "factorial".

3. Define a function named "f2" without any parameters:


a. Initialize a variable "total" with a value of 0.
b. Use a loop to add the first 100 numbers:
i. Initialize a variable "i" with a value of 1.
ii. Repeat the following steps until i reaches 101:
- Add "i" to "total" and assign the result to "total".
- Increment "i" by 1.
c. Return the value of "total".

166 | P a g e
4. Define a function named "f3" without any parameters:
a. Initialize a variable "total" with a value of 0.
b. Use a loop to add the first 50 even numbers:
i. Initialize a variable "i" with a value of 0.
ii. Repeat the following steps until i reaches 101:
- Add "i" to "total" and assign the result to "total".
- Increment "i" by 2.
c. Return the value of "total".

5. End

167 | P a g e
Flowchart:

168 | P a g e
Program:
def f1(n):
"""
Calculate the factorial of a number.
"""
if n < 0:
return "Error: 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

def f2():
"""
Add the first 100 numbers.
"""
total = sum(range(101))
return total

def f3():
"""
Add the first 50 even numbers.
"""
total = sum(range(0, 101, 2))
return total

In this module, f1 calculates the factorial of a given number n, f2 adds the first 100
numbers (from 1 to 100), and f3 adds the first 50 even numbers (from 0 to 100).
To use this module in another Python script, you can import it and call the functions
accordingly:

import operations

# Call f1
factorial_result = operations.f1(5)
print("Factorial:", factorial_result)

# Call f2
sum_result = operations.f2()
169 | P a g e
print("Sum of first 100 numbers:", sum_result)

# Call f3
even_sum_result = operations.f3()
print("Sum of first 50 even numbers:", even_sum_result)

Output:

Factorial: 120
Sum of first 100 numbers: 5050
Sum of first 50 even numbers: 2550

Conclusion :
It is learnt that in conclusion
Modules provide a way to organize related functions, classes, andvariables in a single
file. They promote code reusability and maintainability.
To create a module, define functions, classes, or variables in a Python file.These can
be imported and used in other scripts.
Packages are directories that contain multiple modules and can havenested sub-
packages.

References :
 Modules: https://docs.python.org/3/tutorial/modules.html
 Packages: https://docs.python.org/3/tutorial/modules.html#packages
 Python Modules: https://www.geeksforgeeks.org/python-modules/
 Python Packages: https://www.geeksforgeeks.org/packages-in-python/

170 | P a g e
Practical no. 10

TITLE: Learn python program for using turtle commands in python.

AIM: To write programs for using turtle commands in python.

PROGRAMS:

 Creating shapes using turtle

THEORY –

To create a basic turtle program in Python, you can use the built-in turtle module. The turtle module
allows you to control a turtle graphic on a screen and make it move and draw shapes. The turtle
module in Python provides a set of functions and methods to control a turtle graphic on a screen.
Here are some of the commonly used functions and methods available in the turtle module:

These are just a few of the functions and methods available in the turtle module. There are many
more functions and additional settings that allow you to control the turtle's appearance and
behavior.

171 | P a g e
Method Parameter Functionality

Turtle() None Creates a Turtle object to draw

forward() Distance (in pixels) Moves the Turtle object by the specified
amount of pixels in the forward direction

backward() Distance (in pixels) Moves the Turtle object by the specified
amount of pixels in the backward direction

right() Angle Rotates the Turtle object in the clockwise


direction by the specified angle

left() Angle Rotates the Turtle object in the anti-


clockwise direction by the specified angle

penup() None Lifts the Turtle’s pen

pendown() None Places down the Turtle’s pen

color() Color name Changes the color of the Turtle’s pen to the
specified color

fillcolor() Color name Changes the fill color of the Turtle’s pen

position() None Returns the coordinates of the current


location of the object

172 | P a g e
173 | P a g e
goto() x & y coordinate Moves the Turtle object to the specified
location

done() None Display the figure on the screen

Program:
# Python program to demonstrate
# spiral circle drawing

import turtle

t = turtle.Turtle()

# taking radius of initial radius


r = 10

# Loop for printing spiral circle


for i in range(100):
t.circle(r + i, 45)
t.fillcolor("red")
t.begin_fill()

Output:

174 | P a g e
Programs:

import turtle

ttl = turtle.Turtle()
ttl.forward(150) # moving the turtle Forward by 150 units
ttl.left(90) #Turning the turtle by 90 degrees
ttl.forward(150)
ttl.left(90)
ttl.forward(150)
ttl.left(90)
ttl.forward(150)
ttl.left(90)

Output :

Programs:

#Python Program to draw a star filled with color in Turtle


import turtle
ttl = turtle.Turtle()

#Providing the color to be filled


ttl.color("magenta")

#Instructing to "begin" and "end" filling the "star"


ttl.begin_fill()
175 | P a g e
#for-loop to run 5 times to complete drawing a complete star
for j in range(5):
ttl.forward(200)
ttl.right(144)
ttl.end_fill()

#hiding the turtle after completing the drawing


ttl.hideturtle()
turtle.done()

Output:

Conclusion:
With the turtle module, you can create interactive programs that allow users to draw and explore
various patterns, shapes, and designs. By combining the available functions and methods, you
can create complex and intricate turtle graphics.
The turtle module is beginner-friendly and provides an intuitive way to introduce programming
concepts such as loops and conditional statements. It is often used as a teaching tool for
introducing programming and computational thinking to beginners.
Reference:
https://docs.python.org/3/library/turtle.html
https://www.geeksforgeeks.org/turtle-graphics-python/
https://www.programiz.com/python-programming/examples/turtle-graphics

176 | P a g e

You might also like