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
2 Answers 2
To use 1 loop, you may need to recognize the differences:
- You use 2 simple variables for the results though you could use 1
list. - The input string is almost the same except for "first" and "second" words.
Concept:
- First you want a
list. - Then use a
forloop to use "first", then "second" words. - Then use a
whileloop which processes the inputs and uses thelistto extend with the replies. Usebreakto get out of thewhileloop 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.
1 Comment
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