Eman
Eman

Reputation: 27

validate user input and loop until correct

I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.

Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.

I've attached the part I need help with (yes this is a school assignment):

def get_numbers():
first_number = 0.0
second_number = 0.0

while True:
    try:
        first_number = float(input("Please enter the first number: "))
        second_number = float(input("Please enter the second number: "))
    except ValueError:
        print("Not a valid input, please try again.")
        continue

    return first_number, second_number

Upvotes: 0

Views: 333

Answers (2)

michael_heath
michael_heath

Reputation: 5372

To use 1 loop, you may need to recognize the differences:

  1. You use 2 simple variables for the results though you could use 1 list.
  2. The input string is almost the same except for "first" and "second" words.

Concept:

  1. First you want a list.
  2. Then use a for loop to use "first", then "second" words.
  3. Then use a while loop which processes the inputs and uses the list to extend with the replies. Use break to get out of the while loop after each good reply.

def get_numbers():
    result = []

    for item in ("first", "second"):
        while True:
            try:
                number = float(input("Please enter the " + item + " number: "))
            except ValueError:
                print("Not a valid input, please try again.")
            else:
                result += [number]
                break

    return tuple(result)

Returning as a tuple as you have done.

Upvotes: 2

anonymoose
anonymoose

Reputation: 868

First, you want to use two loops, one for each number, and break if the input is valid instead of continuing if it's invalid. Then you need to move the return statement to immediately following the second loop.

By the way, you can leave out the initial assignments to first_number and second_number (commented out below). Assigning them to float(input(...)) is enough.

def get_numbers():
    #first_number = 0.0
    #second_number = 0.0

    while True:
        try:
            first_number = float(input("Please enter the first number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    while True:
        try:
            second_number = float(input("Please enter the second number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    return first_number, second_number

Upvotes: 0

Related Questions