8) b. try, except statements Examples




You are the governer of Neverland and is being given a task to report the census of the people is its country. You already have a software that does the same. The input is taken from the user but the input is not validated correctly. A user can enter digits in input but the state name can never have digits. The code breaks in such inputs. Write a code that handles this exception gracefully. You are given the input module of the codebase.

1
2
3
4
Output:
Enter the state name
 343
Digit entered in state name. Exiting gracefully




Muscle Puma is creating an online shoe store that lets user give the shoe size and orders the same shoe. As this is a budding start up, the code is only supposed to handle integers as of now and will handle the float functionality later. Muscle Puma wants to let the input come in float but wants it to be rounded to nearest integer. He was already raising the exception in case float was entered. You don’t want to change the current code and instead want to add a wrapper on top of it to.

1
2
3
4
5
Output:
Please enter your shoe size
 5.3
Changing the size to int
The new shoe size is  5




Ghost Fly is a final semester computer science student and writes a program that calculates the area of a triangle as a final project. He gets the input from user and gets the sides as space separated integers. He wants this to be tested before giving a demo in his class and hence writes a exception handler that checks that 3 sides are entered. If not, prmpt the user to run the code again. Write the program for him.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Program:
#area_of_triangle.py

import sys
def calculate_area(side1, side2, side3):
    pass

 
sides = sys.argv[1:]
try:
    global side1, side2, side3
    side1 = int(sides[0])
    side2 = int(sides[1])
    side3 = int(sides[2])
except(IndexError):
    print('3 values were not entered')
   
calculate_area(side1, side2, side3)
1
2
3
# To run the program
c:/> python area_of_triangle.py 34 53
3 values were not entered