0% found this document useful (0 votes)
14 views5 pages

9th PGM

The document describes three Python programs that use exception handling: 1. A program to handle divide-by-zero errors when calculating price per unit weight. It uses try/except blocks to catch different exception types. 2. A program to validate a voter's age by checking for invalid years of birth. It raises an error which is caught and handled in an except block. 3. A program to validate student marks are between 0-100. It uses try/except to catch out of range errors and prompt for valid input.

Uploaded by

sarguruxerox
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)
14 views5 pages

9th PGM

The document describes three Python programs that use exception handling: 1. A program to handle divide-by-zero errors when calculating price per unit weight. It uses try/except blocks to catch different exception types. 2. A program to validate a voter's age by checking for invalid years of birth. It raises an error which is caught and handled in an except block. 3. A program to validate student marks are between 0-100. It uses try/except to catch out of range errors and prompt for valid input.

Uploaded by

sarguruxerox
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/ 5

EX NO: 9 EXCEPTION HANDLING

DATE: A) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING

AIM:
To write a python program to handle divide by zero error using exception
handling.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for price and weight.
Step 3: Calculate result as price / weight in try block.
Step 4: If ZeroDivisionError arise print Division by Zero.
Step 5: otherwise,
Check for other Errors and display them.
Step 6: Display the price per unit weight in case of no errors.
Step 7: Stop the program.
PROGRAM:
import sys
def main():
price = input('Enter the price of item purchased:')
weight = input('Enter the weight of item purchased:')
try:
if price == '': price = None
try:
price = float(price)
except ValueError:
print('Invalid Inputs: ValueError')
if weight == '': weight = None
try:
weight = float(weight)
except ValueError:
print('Invalid Inputs: ValueError')
assert price >= 0 and weight >= 0
result = price / weight
except TypeError:
print('Invalid Inputs: TypeError')
except ZeroDivisionError:
print('Invalid Inputs: ZeroDivisionError')
except:
print(str(sys.exc_info()))
else:
print('Price per unit weight:',result)
if __name__ == '__main__':
main()
OUTPUT 1:
Enter the price of item purchased:20
Enter the weight of item purchased:x
Invalid Inputs: ValueError
Invalid Inputs: TypeError
OUTPUT 2:
Enter the price of item purchased:-20
Enter the weight of item purchased:10
(<class 'AssertionError'>, AssertionError(), <traceback object at
0x0000026F1294BBC0>)
OUTPUT 3:
Enter the price of item purchased:20
Enter the weight of item purchased:0
Invalid Inputs: ZeroDivisionError
OUTPUT 4:
Enter the price of item purchased:20
Enter the weight of item purchased:
Invalid Inputs: TypeError
OUTPUT 5:
Enter the price of item purchased:-20
Enter the weight of item purchased:0
(<class 'AssertionError'>, AssertionError(), <traceback object at
0x0000028FAFAB3B80>)
OUTPUT 6:
Enter the price of item purchased:20
Enter the weight of item purchased:2
Price per unit weight: 10.0
Result:
Thus, the above program was executed successfully and the output was
verified.
EX NO: 9 EXCEPTION HANDLING
DATE: b) VOTER’S AGE VALIDITY

AIM:
To write a python program to check Voter’s age validity.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the year of birth from user.
Step 3: Calculate age by subtracting year of birth from current year.
Step 4: Check whether the age is less than 0 inside try block.
Step 4.1: Then raise Invalid year of birth error.
Step 5: Handle the error in except block.
Step 6: If Age is less than or equal to 18,
print “You are eligible to vote”.
Step 7: Otherwise,
print “You are not eligible to vote”
Step 8: Stop the program.
PROGRAM:
import datetime
Year_of_birth = int(input("Enter your year of birth:- "))
Current_year = datetime.datetime.now().year
Current_age = Current_year-Year_of_birth
try:
if Current_age < 0:
raise ValueError('Invalid Year of Birth')
except:
print('Invalid Year of Birth:Value Error')
Year_of_birth = int(input("Enter your correct year of birth:- "))
Current_age = Current_year-Year_of_birth
print("Your current age is ",Current_age)
if(Current_age<=18):
print("You are not eligible to vote")
else:
print("You are eligible to vote")
OUTPUT 1:
Enter your year of birth:- 1984
Your current age is 39
You are eligible to vote
OUTPUT 2:
Enter your year of birth:- 2026
Invalid Year of Birth:Value Error
Enter your correct year of birth:- 1981
Your current age is 42
You are eligible to vote
Result:
Thus, the above program was executed successfully and the output was
verified.
EX NO: 9 EXCEPTION HANDLING
DATE: c) STUDENT MARK RANGE VALIDATION
AIM:
To write a python program to perform student mark range validation
ALGORITHM:
Step 1: Start the program.
Step 2: Read student mark from user.
Step 3: If the mark is in between 0 and 100,
print “The mark is in the range”
Step 4: Otherwise,
print “The value is out of range”
Step 5: Stop the program.
PROGRAM:
def getMark(subject):
print("Subject:",subject)
mark = int(input('Enter the mark:'))
try:
if mark < 0 or mark > 100:
raise ValueError('Marks out of range')
else:
return mark
except ValueError:
print('Invalid Input: ValuError')
mark = int(input('Enter valid mark(0 - 100):'))
return mark
finally:
print('Processing Wait......')
def main():
a = getMark(subject = 'English')
b = getMark(subject = 'Math')
c = getMark(subject = 'Physics')
d = getMark(subject = 'Chemistry')
e = getMark(subject = 'Python')
avg = ((a+b+c+d+e)/500)*100
if avg >= 80:
print('Congrats! You have secured First Class & ur percentage is',avg)
elif avg >= 60 and avg < 80:
print('Congrats! You have secured Second Class & ur percentage is',avg)
elif avg >= 50 and avg < 60:
print('Congrats! You have secured Third Class & ur percentage is',avg)
else:
print('Sorry! You are Fail. Try again......')
print('End of Program')
main()
OUTPUT:
Subject: English
Enter the mark:102
Invalid Input: ValuError
Enter valid mark(0 - 100):96
Processing Wait......
Subject: Math
Enter the mark:65
Processing Wait......
Subject: Physics
Enter the mark:98
Processing Wait......
Subject: Chemistry
Enter the mark:95
Processing Wait......
Subject: Python
Enter the mark:96
Processing Wait......
Congrats! You have secured First Class & ur percentage is 90.0
End of Program

Result:
Thus, the above program was executed successfully and the output was
verified.

You might also like