Home > Software design >  ValueError Exception Handling in a while loop: Repeat only wrong input
ValueError Exception Handling in a while loop: Repeat only wrong input

Time:03-26

I would like the following code to ask the user -in a while loop- to input two integers, handle ValueError Exception, and if all well to print the sum.

My problem is that if the first number passes and the second doesn't, it asks to input the first one all over again.

How do I get it in this case to prompt the second input only?

while True:

try:
    number_1 = int(input("enter the first number: "))
    number_2 = int(input("enter the second number: "))
except ValueError:
    print("please enter numbers only!")
    
else:
    result = number_1   number_2
    print(f" {number_1}   {number_2} = {result}")

Many thanks in advance!

CodePudding user response:

Probably writing a small function to request user for input and handle the ValueError would come handy in here and would be a good practice to use.

Example:

def get_input(show_text:str):
    while True:
        try:
            number = int(input(show_text))
            break
        except ValueError:
            print('Enter number only!') 
    return number


number_1 = get_input('enter the first number: ')
number_2 = get_input('enter the second number: ')
result = number_1   number_2
print(f" {number_1}   {number_2} = {result}")

Example output

enter the first number: 1
enter the second number: a
Enter number only!
enter the second number: f
Enter number only!
enter the second number: 2
 1   2 = 3
  • Related