try except - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: try except (/thread-16452.html) |
try except - timcain007 - Feb-28-2019 I got it to work half way but having little trouble with input. if the user enters the correct height but enters a str for width. it goes back to asking height. i need it to ask for width again and then get the area. any help or direction pls. Write a program that reads the dimension of a rectangle and prints its area. The program must handle errors such invalid input. If it encounters an error, it should ask the user to reenter the input. def ask_for_int(): #function to get input from user while True: try: # while loop to continually try and except instead of ending num1 = int(input('Enter height: ')) num2 = int(input('Enter width: ')) except: print('is not a valid input. Try again') continue else: print('The area is {}'.format(num1*num2)) break ask_for_int()output>>>> Enter height: 10 Enter width: ddd is not a valid input. Try again Enter height: 10 Enter width: 10 The area is 100 RE: try except - Yoriz - Feb-28-2019 use separate try/except loop for each input. RE: try except - timcain007 - Feb-28-2019 seem to be getting the same result. unless i'm not adding the separate try/except properly. any guidance pls. RE: try except - Yoriz - Feb-28-2019 try to code this get the first input, check for errors if ok move on otherwise ask for input again get the second input, check for errors if ok move on otherwise ask for input again output calculation |