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

Python Final Lab Manual (1)

The lab manual for the AI & ML - B course outlines the objectives and experiments for the Python Programming Laboratory. It includes various programming tasks such as solving technical problems, implementing applications using Python data structures, and handling files and exceptions. Each experiment is designed to enhance understanding of Python programming constructs and real-world problem-solving strategies.

Uploaded by

devi murugan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Final Lab Manual (1)

The lab manual for the AI & ML - B course outlines the objectives and experiments for the Python Programming Laboratory. It includes various programming tasks such as solving technical problems, implementing applications using Python data structures, and handling files and exceptions. Each experiment is designed to enhance understanding of Python programming constructs and real-world problem-solving strategies.

Uploaded by

devi murugan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

LAB MANUAL

CLASS : AI & ML - B
SEMESTER : II
SUBJECT : AI24221/PYTHON PROGRAMMING LABORATORY

OBJECTIVES:
To understand the problem solving approaches.

To learn the basic programming constructs in Python.

To practice various computing strategies for Python-based solutions to real world
problems.
To use Python data structures–lists, tuples, dictionaries.
To do input/output with files in Python.

LISTOFEXPERIMENTS:
1. Identification and solving of simple technical problems, and developing flowcharts for
the same.
2. Python programming using simple statements and expressions.
3. Scientific problems using Conditionals and Iterative loops.
4. Implementing real-time applications using Lists, Tuples.
5. Implementing technical applications using Sets, Dictionaries.
6. Implementing programs using Functions.
7. Implementing programs using Strings.
8. Implementing programs using written modules and Python Standard Libraries.
9. Implementing technical applications using File handling.
10. Implementing real-time applications using Exception handling.
AI24221–PYTHON PROGRAMMING LABORATORY

S.NO. NAMEOFTHEPROGRAM
1 Identification and solving of simple real life or scientific or technical
Problems developing flowchart for the same.
1.1 Electricity Billing
1.2 Python program for sin series
2 Python programming using simple statements and expressions
2.1 Exchanging the values of two variables in python
2.2 Circulate the values of n variables
3 Scientific problems using Conditionals and Iterative loops.
3.1 Number Series-Fibonacci Series
3.2 Number Series-Odd Numbers
4 Implementing real-time applications using Lists, Tuples.
4.1. Basic operations of List
4.2. Library functions using list.
4.3 Components of a car using tuples.
5. Implementing technical applications using Sets, Dictionaries.
5.1 Languages using dictionaries
5.2 Components of Automobile using dictionaries
6 Implementing programs using Functions.
6.1 Square root of a given number using Newton’s method.
6.2 Factorial of a number using functions
7 Implementing programs using Strings.
7.1 Reverse of a string
7.2 Palindrome of a string
8 Implementing programs using written modules and Python
Standard Libraries.
8.1 Convert list into a Series using pandas
8.2 Finding the elements of a given array is zero using numpy
9 Implementing technical applications using File handling.
9.1 Command Line Arguments(Word Count)
9.2 Find the longest word(File handling)
10 Implementing real-time/technical applications using Exception
handling.
10.1 Divide by zero error–Exception Handing
10.2 Voter’s age validity
Ex:1.1
Date: ELECTRICITY BILLING

Aim:
To write a python program to print electricity bill.

Algorithm:

Step 1: Start the program


Step 2 : Read the current reading in cr and previous reading in pr
Step 3 : Calculate total consumed by subtracting cr with pr
Step 4 : if total consumed is between 0 and 101, print amount to pay is consumed * 2
Step 5 : iftotalconsumedisbetween100and201,printamounttopayisconsumed*3 Step 6 :
iftotalconsumedisbetween200and501,printamounttopayisconsumed*4 Step 7 :
if total consumed is greater than 500, print amount to pay is consumed * 5
Step 8 : if total consumed is less than one print in valid reading
Step 9 : Stop

.
Flowchart:
Program:
Cr = int(input("Enter current month reading"))
pr=int(input("Enter previous month reading"))
consumed=cr - pr
if(consumed>=1andconsumed<=100):
amount=consumed * 2
print("your bill is Rs.", amount)
elif(consumed>100andconsumed<=200):
amount=consumed * 3 print("your bill is Rs.",amount)
elif(consumed>200andconsumed<=500):
amount=consumed * 4 print("your bill is Rs.",amount)
elif(consumed>500):
amount=consumed * 5 print("your bill is Rs.",amount)
else:
print("Invalid reading")

Output:
Enter current month reading 500
Enter previous month reading 200
your bill is Rs. 1200

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program for generating electricity bill is executed and the results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:1.2
Date: PYTHON PROGRAM FOR SIN SERIES

Aim:

To write a python program for sin series.

Algorithm:

Step1: Start
Step 2 : Read the values of x and
n Step 3 : Initialize sine=0
Step4: Define a sine function using for loop, first convert degrees to radians.
Step 5 : Compute using sine formula expansion and add each term to the sum variable.
Step 6 : Print the final sum of the expansion.
Step7: Stop.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


FlowChart:

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Program:
import math
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))sine = 0
for i in range(n):
sign=(-1)**i
pi=22/7
y=x*(pi/180)
sine=sine+((y**(2.0*i+1))/math.factorial(2*i+1))*sign print(sine)

Output:

Enter the value of x in degrees:3


Enter the number of terms:2
0.05235699888420977

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program for sin series is executed and the results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:2.1
EXCHANGING THE VALUES OF TWO VARIABLES IN PYTHON
Date:

Aim:

To write a python program to Exchanging the values of two variables taking input from the user.

Algorithm:

Step 1:Start
Step 2:Define a function named format()
Step 2 : Read the input values X and Y
Step 3 : Perform the following steps
Step3.1:temp=x
Step 3.2 : x = y
Step3.3:y=temp
Step 4 : Print the swapped value as result
Step 5 : End

Program:
Using Temporary variable

#To take inputs from the user


x=input('Enter value of x:')
y=input('Enter value of y:')
#create a temporary variable and swap the values
temp = x
x=y
y= temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)

output:
Enter value of x:10
.
Enter value of y:20
The value of x after swapping:20
The value of y after swapping:10

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Few Other Methods to Swap variables Without Using Temporary variable
Program:
x =5
y =10
x, y = y, x
print("x=",x)
print("y=",y)
output:
x =10
y =5

Using Addition and Subtraction Program:


x =15
y =10
x=x+y y
=x-yx
=x– y
print('The value of x after swapping: 'x)
print('The value of y after swapping: 'y)
output:
x =10
y =15

Using Multiplication and Division Program:


x =25
y =10
x=x*y y
=x/yx
=x/y
print('The value of x after swapping: 'x)
print('The value of y after swapping: 'y)
output:
>>>x10.0
>>>y25.0

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Swapping using XOR:
x =35
y = 10
x=x^y
y=x^y x
= x ^y

output:
>>>x
10
>>>y
35

.
Result : Thus the Python program to exchange the values of two variables was executed successfully
and the output is verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:2.2
CIRCULATE THE VALUES OF N VARIABLES
Date:

Aim:

To write a python program to Circulate the values of n variables taking in put from the user.

Algorithm:

Step1: Start
Step2: Declare a list
Step 3: Read number of input value.
Step 4: Store the value of in put in list.
Step 5: Print the original list.
Step 6: Use range function with for loop to circulate the values
Step 7 : Print the result

Program:

A=list(input("Enter the list Values:"))


print(A)
for i in range(1,len(A),1):
print(A[i:]+A[:i])
Output:

EnterthelistValues:'0123'
['0','1', '2', '3']
['1','2','3','0']
['2','3','0','1']
['3','0','1','2']

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result : Thus the Python program to Circulate the values of n variables was executed Successfully and the
output is verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:3.1
NUMBER SERIES-FIBONACCI SERIES
Date:

Aim:
To write a python program to print Fibonacci series taking input from the user.

Algorithm:

Step 1: Start

Step2: Read the input values using input()

Step 3 : Assign f1= -1 and f2=1.


Step 4 : Perform the term = f1+f2
Step 5 : Print the value as result
Step6: Perform the following swap
Step 7 : step f1 = f2
Step8: f2=term Step
9 : End

Program:

# Fibonacci series
print("Fibonacci series")
Num_of_terms=int(input("Enter number of terms:"))
f1 = -1
f2 =1
for i in range(0,Num_of_terms,1): term
= f1+f2
print(term,end="") f1 =
f2
f2 =term
Output:
Fibonacci series :
Enter number of terms:5
01123

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result : Thus the Python program to print Fibonacci series was executed successfully and the output is
verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:3.2
NUMBER SERIES-ODD NUMBERS
Date:

Aim:
To write a python program to print odd numbers by taking input from the user
Algorithm:

Step1: start
Step 2 : Declare the list of numbers using list.

Step 3 : Use for loop to iterate the numbers in list.


Step 4 : Check for condition
Step 5 : Num % 2==0
Step 6 : Print the
result. Step 7 : End

Program:

#list of numbers
list1= [10,21, 4,45, 66, 93]
#iterating each number in list
for num in list1:
#checking condition
if num % 2 != 0:
print(num,end="")

Output:
Enter number of terms: 5
Number Patterns-Odd Numbers:
13579

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result : Thus the Python program to print odd numbers was executed successfully and the output is
verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Ex:4.1
IMPLEMENTING REAL-TIME APPLICATIONS USING
Date: LISTS BASIC OPERATIONS OF LIST

Aim:

To write python programs using list functions to perform the operations of list library.
Algorithm:

Step1: Start
Step2: Declare a list
Step3: Read the input value.
Step4: Store the value of input in list.
Step 5 : Process the list functions present in library function.
Step 6 : Print the result
Step7: End

Program:

#creatingalist

Library=['OS','OOAD','MPMC']
print("Books in library are:")
print(Library)

OUTPUT:
Books in library are:
['OS','OOAD','MPMC']

#Accessing elements from the List


Library=['OS','OOAD','MPMC']
print("Accessing a element from the list") print(Library[0])
print(Library[2])

OUTPUT:
Accessing a element from the list OS MPMC

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


#Creating a Multi-Dimensional List
.
Library=[['OS','OOAD','MPMC'],['TOC','PYTHON','NETWORKS']]
print("Accessing a element from a Multi-Dimensional list")
print(Library[0][1])
print(Library[1][0])

OUTPUT:
Accessing a element from a Multi-Dimensional list OOAD TOC

#Negative indexing
Library=['OS','OOAD','MPMC']
print("Negative accessing a element from the list")
print(Library[-1])
print(Library[-2])

OUTPUT:
Negative accessing a element from the list MPMC OOAD

#Slicing
Library=['OS','OOAD','MPMC','TOC','NW']
print(Library[1][:-3])
print(Library[1][:4])
print(Library[2][2:4])
print(Library[3][0:4])
print(Library[4][:])

OUTPUT:
OS OOAD MC TOC NW

#append()
Library=['OS','OOAD','MPMC']
Library.append(“DS”)
Library.append(“OOPS”)
Library.append(“NWs”)
print(Library)

OUTPUT:
['OS','OOAD','MPMC','DS','OOPS','NWs']

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


#extend()
Library=['OS','OOAD','MPMC']
Library.extend(["TOC","DWDM"])
print(Library)

OUTPUT:
['OS','OOAD','MPMC','TOC','DWDM']

#insert()
Library=['OS','OOAD','MPMC']
Library.insert(0,”DS”)
print(Library)

OUTPUT:
['DS','OS','OOAD','MPMC']

#del method
Library=['OS','OOAD','MPMC']
delLibrary[:2]
print(Library)

OUTPUT:
['MPMC']

#remove()
Library=['OS','OOAD','MPMC','OOAD']
Library.remove('OOAD')
print(Library)

OUTPUT:
['OS','MPMC','OOAD']

#reverse()
Library=['OS','OOAD','MPMC']
Library.reverse()
print(Library)

OUTPUT:
['MPMC','OOAD','OS']

#sort()
Library=['OS','OOAD','MPMC']
Library.sort()
print(Library)

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


OUTPUT:
['MPMC','OOAD','OS']

#+concatenation operator
Library=['OS','OOAD','MPMC']
Books=['DS','TOC','DMDW']
print(Library+Books)

OUTPUT:
['OS','OOAD','MPMC','DS','TOC','DMDW']

# *replication operator
Library=['OS','OOAD','MPMC','TOC','NW']
print('OS' in Library)
print('DWDM' in Library)
print('OS' not in Library)

OUTPUT:
True
False
False

#count()
Library=['OS','OOAD','MPMC','TOC','NW']
x=Library.count("TOC")
print(x)

OUTPUT: 1

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result : Thus the Python using list function present in list library was execute successfully and the

output is verified

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Ex:4.2
LIBRARY FUNCTIONALITY USING LIST.
Date:

Aim:
To write a python program to implement the library functionality using list.

Algorithm:
Step 1 : Start the program
Step 2 : Initialize the booklist
Step3: Get option from the user for accessing the library function
Add the book to list
Issue a book
Return the book
View the list of book
Step4: if choice is1 then get book name and add to book list
Step 5 : if choice is 2 then issue the book and remove from book list
Step6: if choice is 3 then return the book and add the book to list
Step 7 : if choice is 4 then the display the book list
Step 8 : otherwise exit from menu
Step 9 : Stop the program.

Program:

bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input("\n1.addthebooktolist\n2.issueabook\n3.returnthebook\n4.viewthe book list \n 5.
Exit \n"))
if(ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break .

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Output:
Welcome to library”
1. Add the book to list
2. Issue a book
3. Return the book
4. View the book list
5. Exit
1
enter the book name NW
['OS','MPMC','DS','NW']
1. Add the book to list
2. Issue a book
3. Return the book
4. View the book list
5. Exit
2
Enter the book to issue
NW['OS','MPMC','DS']
1. Add the book to list
2. Issue a book
3. Return the book
4. View the book list
5. Exit
3
enter the book to return
NW['OS','MPMC','DS','NW']
1. Add the book to list
2. Issue a book
3. Return the book
4. View the book list
5. Exit
4
['OS','MPMC','DS',' NW']

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program to implement the library functionality using list is executed and the
Results are verified
.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:4.3
COMPONENTS OF CAR USING LIST
Date:

Aim:
To write a python program to implement the operation of list for components of car.

Algorithm:

Step1: Start the program.


Step2: Create a list of components for car
Step 3 : Get single component from user and append in to list

Step 4 : Find the length of the list using len function


Step 5 : Find the minimum and maximum value of the list
Step 6 : Print the component using index of the list
Step7: Multiply the list element using multiplication operation
Step 8 : Check the component exist in the list or not using in operator
Step 9 : Stop the program.

Program:
cc=['Engine','Frontxle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print("Components of car :",cc)
print("length of the list:",len(cc))
print("maximum of the list:",max(cc))
print("minimum of the list:",min(cc))
print("indexing(Value at the index 3):",cc[3])
print("Return 'True' if Battery is present in the list")
print("Battery" in cc)
print("multiplication of list element:",cc*2)

.
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Output: Enter the car components : Glass
Components of car:['Engine','Frontxle','Battery','transmision','Glass'] length
of the list: 5
maximum of the list: transmission minimum of the list: Battery
indexing(Valueattheindex3):transmision
Return 'True' if Battery is present in the list True
Multiplication of list element:['Engine','Frontxle','Battery','transmision','Glass', 'Engine',
'Front xle', 'Battery', 'transmision', 'Glass']

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result : Thus the python program to create a list for components of car and performed the various operation
and result is verified.
.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:5.1 IMPLEMENTING TECHNICAL APPLICATIONS USING SETS,
Date: DICTIONARIES.

Aim:
To write a python program to implement the languages using dictionaries.

Algorithm:
Step1 : Start the program
Step2: Create a empty dictionary using{}
Step 3 : dict() is used to create a dictionary.
Step 4 : To add a value, update() is used in key value pair.
Step 5 : Calculate the total values in the dictionary using len() .
Step 6 : Remove the particular key in the dictionary by using pop()
Step 7 : Print the keys in the dictionary by using key()
Step 8 : Print the values in the dictionary by using values()
Step 9 : Print the key value pair in the dictionary using items()
Step 10 : Clear the the key value pair by using clear()
Step11: Delete the dictionary by using del dictionary

Program:
Language={}
print("Empty Dictionary:",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4:"hindi",5:"hindi"}
#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
print("the length of the languages:",len(Language))
Language.pop(5)
print("key5hasbeenpoppedwithvalue:",Language)
print(" the keys are :",Language.keys())
print("the values are :",Language.values())
print("the items in languages are:",Language.items())
Language.clear()
.
print(Language)

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


print("The items are cleared in dictionary",Language)
del Language
print(Language)

OUTPUT:

Empty Dictionary:{}

Using dict()the languages are:{1:'english',3:'malayalam','two':'tamil'}

The updated languages are:{1:'english',3:'malayalam',4:'hindi','two':'tamil',5:'hindi'} the

length of the languages : 5

Key 5 has been popped with value:{1:'english',3:'malayalam',4:'hindi','two':'tamil'} the

keys are : dict_keys([1, 3, 4, 'two'])

The values are:dict_values(['english','malayalam','hindi','tamil'])

The items in languages are:dict_items([(1,'english'),(3,'malayalam'),(4,'hindi'),('two', 'tamil')])

The items are cleared in dictionary{}


Trace back (most recent call last):
File"C:/PortablePython3.2.5.1/3.py",line17,in<module>print(Language)
Name Error: name 'Language' is not defined

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program to implement languages using dictionaries is executed and verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:5.2
Date: COMPONENTS OF AUTOMOBILE USING DICTIONARIES

Aim:
To write a python program to implement automobile using dictionaries.

Algorithm:
Step1: Start the program
Step2: Create a empty dictionary using{}
Step3: dict() is used to create a dictionary.
Step4: Get the value in the dictionary using get()
Step5: adding[key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using pop item().
Step7: To check whether key is available in dictionary by using membership operatorin.
Step 8: Stop the program.

Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print("Thevaluefor2is",auto_mobile.get(2))
auto_mobile['four']="chassis"
print("Updatedauto_mobile",auto_mobile)print(auto_mobile.popitem()) print("
The current auto_mobile parts is :",auto_mobile)
print("Is 2 available in automobile parts")
print(2 in auto_mobile)

OUTPUT:

Empty dictionary{}
Auto mobile parts:{1:'Engine',2:'Clutch',3:'Gearbox'}The value
for 2 is Clutch
Updatedauto_mobile{1:'Engine',2:'Clutch',3:'Gearbox','four':'chassis'}(1,'Engine') The
current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is 2 available in automobile parts True

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program to implement automobile using dictionaries is executed and verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:6.1
GCD OF GIVEN NUMBERS USING EUCLID'S ALGORITHM.
Date:

Aim:
To write a python program to find gcd of given numbers using Euclid’s algorithm.

Algorithm:

Step1: Start the program.


Step 2: Read the values of a and b as positive integers in function call gcd(a,b).
Step3: Recursively function call gcd(a,b) will be compute din(b,a%b) ifb!=0.
Step 4: if b is equal to 0 return a.
Step 5: Print the result.
Step6: Stop the program.

Program:

defgcd(a, b):
if(b==0):
return a
else:
return gcd(b, a % b)
a=int(input("Enter the value of a"))
b=int(input("Enter the value of b"))
result=gcd(a,b)
print("The greatest common divisor is",result)

Output:
Enter the value of a 24
Enterthevalueofb54
Thegreatestcommondivisoris6

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program to find gcd of given numbers using Euclid’s method is executed and
the results are verified.
. .

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:6.2
Date: SQUARE ROOT OF A GIVEN NUMBER USING NEWTONS METHOD

Aim:
To write a python program to find to find square root of a given number using newtons method.

Algorithm:

Step1: Start the program.


Step2: Read the value of n,n being a positive integer in the function newton Sqrt(n)
Step 3: Let approx = 0.5 * n
Step4: Let better =0.5* (apporx+ n/approx)
Step5: Repeat the following steps until better equals to approx
Step 5.1: Let approx = better
2:Letbetter =0.5* (apporx+ n/approx)
Step 6: Return the value approx as the square root of the given number n
Step 7: Print the result.
Step 8: Stop the program.

Program:

def newton Sqrt(n):

approx= 0.5 * n
better=0.5*(approx+n/approx)
while(better != approx):
approx= better
better=0.5*(approx+n/approx) return
approx
n=int(input("Enter the number"))
result=newton Sqrt(n)
print("The Square root for the given number is", result)

OUTPUT:
Enter the number 25
The Square root for the given number is 5.0

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result: Thus the python program to find square root of given number using newtons method is executed
and the results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:7.1
REVERSE OF A STRING
Date:

Aim:
To write a python program for reversing a string.

Algorithm:

Step1: Start the program.


Step2: Read the value of a string value by using function call reversed_string.
Step 3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].
Step 5: Print a
Step6: Stop the program

Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)

Output:
dlroW,olleH

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Result
: Thus the python program for reversing a.string is executed and the results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:7.2
PALINDROME OF A STRING
Date:

Aim:
Towriteapythonprogramforpalindromeofastring.
Algorithm:
Step1:Startthe program.
Step 2:Read the valueof a string value by using inputmethod.
Step3:ifstring==string[::-1],print“thestringispalindrome”. Step
4: else print “ Not a palindrome ”.
Step5:Stop the program

Program:
string=input(("Enterastring:"))
if(string==string[::-1]):
print("Thestringisapalindrome")
else:
print("Notapalindrome")

Output:
Enter a string: madam
Thestringisapalindrome
Enter a string: nice
Notapalindrome

Result:
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
areverified.
Thusthe pythonprogram forpalindromeofa stringisexecutedandthe results
.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:7.3
Date: Charactercountofastring

Aim:
Towriteapythonprogramforcountingthecharactersof string.

Algorithm:

Step1:Starttheprogram. Step
2: Define a string.
Step2:Defineandinitializeavariablecountto 0.
Step3:Iteratethroughthestringtilltheendandforeachcharacterexceptspaces,increment the count
by 1.
Step4:Toavoidcountingthespaceschecktheconditioni.e.string[i]!=''.
Step5:Stopthe program.

Program:

a=input("enterthe
string") count = 0;
#Countseachcharacterexcept
space for i in range(0, len(a)):
if(a[i]!=''):
count = count+ 1;
#Displaysthetotalnumberofcharacterspresentinthegivenstring print("Total
number of characters in a string: " + str(count));

Output:
enterthestringhai
Totalnumberofcharactersinastring:3

Result:Thusthepythonprogramforcountingthecharactersofstringisexecutedandtheresultsare verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


verified.
.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:7.4
Replaceofastring
Date:

Aim:
Towriteapythonprogramforreplacingthecharactersofastring.

Algorithm:

Step1:Starttheprogram. Step 2:
Define a string.
Step3:Determinethecharacter'ch'throughwhichspecificcharacterneedtobereplaced. Step 4:
Use replace function to replace specific character with 'ch' character.
Step5:Stoptheprogram.

Program:

string="Onceinabluemoon" ch
= 'o'
#Replacehwithspecificcharacterch string
= string.replace(ch,'h')
print("Stringafterreplacingwithgivencharacter:")
print(string)

Output:
Stringafterreplacingwithgiven character:
Once in a blue mhhn

Result:
Thusthepython programforreplacing thegivencharactersofstringisexecuted
andtheresultsare verified.

60

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:8.1
Date: ConvertlistintoaSeriesusingpandas

Aim:
TowriteapythonprogramforconvertinglistintoaSeries.

Algorithm:

Step 1: Start the program.


Step2:importpandaslibrary
Step3:Createaobjectaspdforpandas. Step
4: Define a list
Step4:Convertthelistintoseriesbycallingtheseriesfunction Step 4:
print the result
Step5:Stoptheprogram.

Program:

#Tousepandasfirstwehavetoimportpandas import
pandas as pd
#Herepdjustaobjectofpandas
#Defining a List
A=['a','b','c','d','e']
#Convertingintoaseries
df=pd.Series(A)print(df)

Output:
1 a
2 b
3 c
4 d
5 e
dtype: object

Result:
Thusthepythonprogramforconvertinglistintoaseriesisexecuted and the
results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:8.2
Date: Findingtheelementsofagivenarrayiszerousingnumpy

Aim:
Towriteapythonprogramfortestingwhethernoneoftheelements ofagivenarrayis zero.

Algorithm:

Step 1 : Start the program.


Step 2 : importnumpylibrary
Step 3 : Createaobjectasnpfornumpylibrary
Step 4 : Define and initialize an array
Step 5 : totestifnoneoftheelementsofthesaidarrayiszerouseallfunction Step 6 :
print the result
Step7: Stopthe program.

Program:

import numpy as np
#Arraywithoutzerovalue x
= np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))

Output:
Originalarray:
[1 2 3 4]
Testifnoneoftheelementsofthesaidarrayis zero:
True
Originalarray:
[0 1 2 3]
Testifnoneoftheelementsofthesaidarrayis zero:
False

Result:
Thusthe pythonprogram fortesting whethernoneoftheelementsofagivenarrayiszerois

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


executedandtheresultsare verified.
Ex:8.3
Date: Generateasimplegraphusingmatplotlib

Aim:
Towriteapythonprogramforgeneratingasimplegraphusingmatplotlib.
Algorithm:

Step1:Start the program.


Step2:frommatplotlibimportpyplotlibaray Step
3: Create a object as plt for pyplot
Step4:Useplotfunctiontoplotthegivenvalues Step 5:
Plot the result using show function
Step6:Stopthe program.

Program:

frommatplotlibimportpyplotasplt
#Plotting to our canvas plt.plot([1,2,3],
[4,5,1])
#Showingwhatweplotted
plt.show()

Output:

Result:
Thusthepythonprogramforgeneratingasimplegraphusingmatplotlibzeroisexecuted and the
results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:8.4
Date: Solvetrigonometricproblemsusingscipy

Aim:
Towriteapythonprogramforfindingtheexponentsandsolvetrigonometricproblems using
scipy.

Algorithm:

Step1:Start the program.


Step2:fromscipylibarayimportspecialfunction
Step3:Useexponent,sin,cosfunctionstoperformscientificcalculatins Step
5: Plot the result.
Step6:Stopthe program.

Program:

fromscipyimportspecial a
= special.exp10(3)
print(a)
b=special.exp2(3)
print(b)
c=special.sindg(90)
print(c)
d=special.cosdg(45)
print(d)

Output:

1000.0
8.0
1.0
0.707106781187

Result:
Thusthepythonprogramforfindingtheexponentsandsolvetrigonometricproblemsusing scipy is
executed and the results are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:9.1
Date: Copytextfromonefiletoanother

Aim:
TowriteaPythonprogramforcopyingtextfromonefiletoanother.
Algorithm:

Step 1:Start
Step2:Createfilenamedfile.txtandwritesomedatainto it.
Step3:Createafilenamesample.txt tocopythe contentsofthefile
Step4:Thefilefile.txtisopenedusingthe open()functionusingthe fstream.
Step5:Anotherfilesample.txtisopenedusingtheopen()functioninthewritemodeusingthe f1 stream.
Step6:Eachlineinthefileisiteratedoverusingaforloop(intheinputstream). Step 7 : Each
of the iterated lines is written into the output file.
Step8:Stop

Program:
withopen("file.txt")asf:
withopen("sample.txt","w")asf1: for
line in f:
f1.write(line)

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Output:

Thecontentsoffilenamedfile.txtiscopiedinto sample.txt

Result:
Thusthepythonprogramforcopyingtextfrom onefile toanotheris executedandtheresults
are verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:9.2
Date: CommandLineArguments(WordCount)

Aim:
TowriteaPythonprogramforcommandlinearguments.

Algorithm:

Step1:Start
Step2:Importthepackagesys
Step3:Gettheargumentsincommandlineprompt
Step4:Printthenumberofargumentsinthecommandlinebyusinglen(sys.argv)function Step5:
Print the arguments using str(sys.argv ) function
Step6:Stop

Program:
importsys
print('Numberofarguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))

Stepsforexecution:

OpenWindowscommandpromptbytypingcmdinstartupmenu C:\
Users\admin>cd..
C:\Users>cd..
C:\>cd Portable Python 3.2.5.1 C:\
PortablePython3.2.5.1>cdApp
C:\PortablePython3.2.5.1\App>python.execmd.pyarg1arg2arg3
Or
C:\PortablePython3.2.5.1\App>pythoncmd.pyarg1arg2arg3

Output:
Number of arguments: 4 arguments.
ArgumentList:['cmd.py','arg1','arg2','arg3']

Result:
ThusthePythonprogramforcommandlineargumentsisexecutedsuccessfullyandthe output is
verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:9.3
Date: Findthelongestword(Filehandling)

Aim:
TowriteaPythonprogramforfindingthelongestwordsusingfilehandling concepts.

Algorithm:

Step1:Startthe program
Step2:Createatextfilenameitfile.txtandsaveit. Step3:
Open the text file in read mode
Step4:Readthefileandsplitthewordsinthefileseparately. Step4: Find
the word with maximum length
Step5: Print the result.
Step6:Stoptheprogram.

Program:

#Openingfileinreadingmode
file=open("file.txt", 'r')
#Converting in a list
print("Listofwordsinthefile")
words=file.read().split()
print(words)
#Selectingmaximumlengthword
max_len = max(words, key=len)
print("WordwithmaximumLengthis",max_len) for i
in max_len:
iflen(i)==max_len:
print(i)

Output:

Listofwordsin thefile

['hai','this','is','parvathy','how','are','you','all','read','well','all','best','for','university', 'exams.']

WordwithmaximumLengthisuniversity

Result:
ThusthePythonprogramfindingthelongestwordsusingfilehandlingconceptsisexecuted
successfully and the output is verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:10.1
Dividebyzeroerror–ExceptionHanding
Date:

Aim:
TowriteaPythonprogramforfindingdividebyzeroerror.

Algorithm:

Step1:Startthe program
Step2:Takeinputsfromtheuser,twonumbers.
Step 3:Ifthe entered datais not integer,throw anexception.
Step4:Iftheremainderis0,throwdividebyzeroexception. Step
5: If no exception is there, return the result.
Step6:Stopthe program.

Program:

try:
num1 = int(input("Enter First Number: "))
num2=int(input("EnterSecondNumber:"))
result = num1 / num2
print(result)
exceptValueErrorase:
print("InvalidInputPleaseInputInteger...") except
ZeroDivisionError as e:
print(e)

Output:
EnterFirstNumber: 12.5
InvalidInputPleaseInput Integer...

Enter First Number: 12


EnterSecondNumber:0
division by zero

Enter First Number: 12


EnterSecondNumber:2
6.0

Result:
ThusthePythonprogramforfindingdividebyzeroerrorisexecutedsuccessfullyandthe output is
verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:10.2
Voter’sagevalidity
Date:

Aim:
TowriteaPythonprogramforvalidatingvoter’s age.
Algorithm:

Step1:Startthe program
Step2:Accepttheageofthe person.
Step3:Ifageisgreaterthanorequalto18,thendisplay'Youareeligibletovote'. Step 4: If
age is less than 18, then display 'You are not eligible to vote'.
Step5:Iftheentereddataisnotinteger,throwanexceptionvalueerror. Step 6: :
If the entered data is not proper, throw an IOError exception Step 7: If no
exception is there, return the result.
Step8:Stopthe program.

Program:

def main():
#singletrystatementcanhavemultipleexceptstatements. try:
age=int(input("Enteryourage")) if
age>18:
print("'Youareeligibletovote'")
else:
print("'Youarenoteligibletovote'") except
ValueError:
print("agemustbeavalidnumber")
except IOError:
print("Entercorrectvalue")
#genericexceptclause,whichhandlesanyexception.
except:
print("AnErroroccured")
main()

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Output:
Enteryour age20.3
agemustbea valid number

Enter your age 12


Noteligibletovote

Enteryourage35
Eligible to vote

Result:
ThusthePythonprogramforvalidatingvoter’sageisexecutedsuccessfullyandtheoutputis verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:10.2
Studentmarkrangevalidation
Date:

Aim:
Towriteapythonprogramforstudentmarkrangevalidation

Algorithm:

Step1:Start the program


Step2:Gettheinputsfromtheusers.
Step3:Iftheentereddataisnotinteger,throwanexception. Step 4:
If no exception is there, return the result.
Step5:Stopthe program.

Program:

def main():
try:
mark=int(input("Enteryourmark:"))
if(mark>=50 and mark<101):
print("Youhavepassed")
else:
print("Youhavefailed")
except ValueError:
print("Itmustbeavalidnumber") except
IOError:
print("Entercorrectvalidnumber")
except:
print("anerroroccured")
main()

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Output:
Enteryourmark:50
You have passed
Enter your mark:r
Itmustbeavalidnumber Enter
your mark:0
Youhavefailed

Result:
Thusthepythonprogramforstudentmarkrangevalidationisexecutedandverified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:11
ExploringPygame tool.
Date:

Pygame:

Pygame is a set of Python modules designed to make games. It uses


SDL(SimpleDirectMediaLayer)whichisacross-platformlibrarythatabstractsthe multimedia
components of a computer as audio and video and allows an easier development of programs
that uses these resources.

Stepsforinstallingpygamepackage:

1. OpenWindowscommandpromptbytypingcmdinstartupmenu
2. C:\Users\admin>cd..
3. C:\Users>cd..
4. C:\>cdPortablePython3.2.5.1
5. C:\PortablePython3.2.5.1>py-mpipinstall-Upygame–user

OnlineExecutionProcedure:

1. Copythisurl:https://trinket.io/features/pygametoyourbrowserandopen pygame
interpreter
2. Removethesourcecodeinmain.pyandcopythebelowsourcecode to main.py
3. ClicktheRun buttonto execute.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:12.1
SimulateBouncingBallUsingPygame
Date:

Aim:
TowriteaPythonprogramtosimulatebouncingballinpygame.

Algorithm:

Step1:Start

Step2:Importthenecessarypackages

Step3:Initializetheheight,widthandspeedinwhichtheballbounce Step4:Set

the screen mode

Step5:Load theball image

Step4:Movetheballfromlefttoright Step5:

Stop

Program:

importsys,pygame

pygame.init()

size=width,height=700,300

speed = [1, 1]

background=255,255, 255

screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bouncing ball")

ball=pygame.image.load("'C:\\Users\\parvathys\\Downloads\\ball1.png") ballrect

= ball.get_rect()

while1:

foreventinpygame.event.get():

ifevent.type==pygame.QUIT:sys.exit()

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


ballrect= ballrect.move(speed)

ifballrect.left<0orballrect.right>width: speed[0] =

-speed[0]

ifballrect.top<0orballrect.bottom>height:

speed[1] = -speed[1]

screen.fill(background)

screen.blit(ball,ballrect)

pygame.display.flip()

Output:

Result:

ThusthePythonprogramtosimulatebouncingballusingpygameisexecutedsuccessfully and the


output is verified.

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Ex:12.2
CarRace
Date:

Aim:
TowriteaPythonprogramtosimulatecarraceinpygame.

Algorithm:

Step1:Start
Step2:Importthenecessarypackages
Step3:Initializetheheight,widthofthescreenandspeedinwhichthecarcanrace. Step4:Set the
screen mode
Step5:Loadtherequiedimageslikeracingbeast,logo,fourdifferentcarimages Step4:
Move the car on the race track
Step5:Stop
Program:
importpygame
pygame.init()#initializesthePygame
frompygame.localsimport*#importallmodulesfromPygame screen
= pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('Racing Beast')
#changing the logo
logo=pygame.image.load('C:\\Users\\parvathys\\Downloads\\cargame/logo.png')
pygame.display.set_icon(logo)
#definingourgameloopfunction def
gameloop():
#settingbackgroundimage
bg=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame/bg.png') #
setting our player
maincar=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car.png')
maincarX = 100
maincarY=495
maincarX_change=0
maincarY_change=0

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


#other cars
car1=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car1.png')
car2=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car2.png')
car3=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car3.png')
run = True
whilerun:
for event
inpygame.event.get():ifevent.ty
pe==pygame.QUIT:
run = False
ifevent.type==pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
maincarX_change+=5
ifevent.key==pygame.K_LEFT:
maincarX_change -= 5
ifevent.key==pygame.K_UP:
maincarY_change -= 5
ifevent.key==pygame.K_DOWN:
maincarY_change += 5
#CHANGINGCOLORWITHRGBVALUE,RGB=RED,GREEN,BLUE
screen.fill((0,0,0))
#displayingthebackgroundimage
screen.blit(bg,(0,0))
#displaying our main car screen.blit(maincar,
(maincarX,maincarY)) #displaing other cars
screen.blit(car1, (200,100)) screen.blit(car2,
(300,100)) screen.blit(car3,(400,100))
#updatingthe values
maincarX+=maincarX_change
maincarY +=maincarY_change
pygame.display.update()
gameloop()

Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])


Output:

Result:

ThusthePythonprogramtosimulatecarraceusingpygameisexecutedsuccessfullyandthe output is
verified.

Ex:7.1
REVERSE OF A STRING
Date:

Aim:
To write a python program for reversing a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string.
Step 3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program

Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)

Output:
dlroW,olleH
Result:Thus the python program for reversing a.string is executed and the results are verified.
Ex:7.2
PALINDROME OF A STRING
Date:

Aim:
To write a python program for palindrome of a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method.
Step 3: if string==string[::-1],print “the string is palindrome”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop the program

Program:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

Output:
Enter a string: madam
The string is a palindrome
Enter a string: nice
Not a palindrome

Result: Thus the python program for palindrome of a string is executed and the results are verified.
Ex:8.1
Date: CONVERT LIST IN TO A SERIES USING PANDAS

Aim:
To write a python program for converting list into a Series.

Algorithm:

Step 1: Start the program. Step


2: import pandas library
Step 3: Create an object as pd for pandas.
Step 4: Define a list
Step 5: Convert the list into series by calling the series function
Step 6: print the result
Step 7: Stop the program.

Program:

#To use pandas first we have to import pandas


import pandas as pd
#Here pd just a object of pandas
#Defining a List
A=['a','b','c','d','e']
#Converting into a series
df=pd.Series(A)
print(df)

Output:
1 a
2 b
3 c
4 d
5 e
dtype: object

Result: Thus the python program for converting list into a series is executed and the results are
verified.
Ex:8.2
FINDING THE ELEMENTS OF A GIVEN ARRAY IS ZERO USING
Date: NUMPY

Aim:
To write a python program for testing whether none of the elements of a given array is zero.

Algorithm:

Step 1 : Start the program.


Step 2 : import numpy library
Step 3 : Create a object as np for numpy library
Step 4 : Define and initialize an array
Step 5 : to test if none of the elements of the said array is zero use all function
Step 6 : print the result
Step 7: Stop the program.

Program:

import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))

Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False

Result:
Thus the python program for testing whether none of the elements of a given array is zero is
executed and the results are verified.
Ex:9.1
Date: COPY TEXT FROM ONE FILE TO ANOTHER

Aim:
To write a Python program for copying text from one file to another.
Algorithm:

Step 1: Start
Step 2: Create file named file.txt and write some data into it.
Step 3: Create a file name sample.txt to copy the contents of the file
Step 4: The file file.txt is opened using the open() function using the f stream.
Step 5: Another file sample.txt is opened using the open() function in the write mode using the
f1 stream.
Step 6: Each line in the file is iterated over using a for loop (in the input stream).
Step 7: Each of the iterated lines is written into the output file.
Step 8: Stop

Program:
with open("file.txt")as f:
with open("sample.txt","w")as f1:
for line in f:
f1.write(line)
Output:

The contents of file named file.txt is copied into sample.txt

Result: Thus the python program for copying text from one file to another is executed and the results
are verified.
Ex:9.2
Date: COMMAND LINE ARGUMENTS (WORDCOUNT)

Aim:
To write a Python program for command line arguments.

Algorithm:

Step 1: Start
Step 2: import the package sys
Step 3: Get the arguments in command line prompt
Step 4: Print the number of arguments in the command line by using len(sys.argv)function
Step 5: Print the arguments using str(sys.argv ) function
Step 6: Stop

Program:
import sys
print('Number of arguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))

Steps for execution:

Open Windows command prompt by typing cmd in startup menu


C:\Users\admin>cd..
C:\Users>cd..
C:\>cd Portable Python 3.2.5.1 C:\
PortablePython3.2.5.1>cd App
C:\PortablePython3.2.5.1\App>python.exe cmd.py arg1 arg2 arg3
Or
C:\PortablePython3.2.5.1\App>python cmd.py arg1 arg2 arg3

Output:
Number of arguments: 4 arguments.
Argument List: ['cmd.py','arg1','arg2','arg3']

Result: Thus the Python program for command line arguments is executed successfully and the
output is verified.
Ex:10.1
DIVIDE BY ZERO ERROR–EXCEPTION HANDING
Date:

Aim:
To write a Python program for finding divide by zero error.

Algorithm:

Step 1: Start the program


Step 2: Take inputs from the user, two numbers.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step 6: Stop the program.

Program:

try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number:"))
result = num1 / num2
print(result)
except Value Error as e:
print("Invalid Input Please Input Integer...")
except Zero Division Error as e:
print(e)

Output:
Enter First Number: 12.5
Invalid Input Please Input Integer...

Enter First Number: 12


Enter Second Number: 0
division by zero

Enter First Number: 12


Enter Second Number: 2
6.0

Result: Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
Ex:10.2
VOTER’S AGE VALIDITY
Date:

Aim:
To write a Python program for validating voter’s age.

Algorithm:

Step 1: Start the program


Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to18, then display 'You are eligible to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: If the entered data is not integer, throw an exception value error.
Step 6: If the entered data is not proper, throw an IOError exception Step
7: If no exception is there, return the result.
Step 8: Stop the program.

Program:

def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except Value Error:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
Output:
Enter your age 20.3
age must be a valid number

Enter your age 12


Not eligible to vote

Enter your age 35


Eligible to vote

Result: Thus the Python program for validating voter’s age is executed successfully and the output
is verified.
Ex:10.2
STUDENT MARK RANGE VALIDATION
Date:

Aim:
To write a python program for student mark range validation

Algorithm:

Step 1: Start the program


Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program.

Program:

def main():
try:
mark=int(input("Enter your mark:"))
if(mark>=50 and mark<101):
print("You have passed")
else:
print("You have failed")
except ValueError:
print("It must be a valid number")
except IOError:
print("Enter correct valid number")
except:
print("an error occured")
main()
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed

Result: Thus the python program for student mark range validation is executed and verified.

You might also like