Python Forum

Full Version: try except
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
use separate try/except loop for each input.
seem to be getting the same result. unless i'm not adding the separate try/except properly. any guidance pls.
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