Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try except
#1
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
Reply


Messages In This Thread
try except - by timcain007 - Feb-28-2019, 06:13 PM
RE: try except - by Yoriz - Feb-28-2019, 06:15 PM
RE: try except - by timcain007 - Feb-28-2019, 06:34 PM
RE: try except - by Yoriz - Feb-28-2019, 06:40 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020