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
#2
use separate try/except loop for each input.
Reply
#3
seem to be getting the same result. unless i'm not adding the separate try/except properly. any guidance pls.
Reply
#4
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
Reply


Forum Jump:

User Panel Messages

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