Nathan Shoesmith Nathan Shoesmith - 6 months ago 9
Python Question

Looping the function

I have this function below, which I have done something wrong in somewhere.

def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:
try:
int(i)
return int(quantity)
valid = True
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
return True

return False


To run through, the function is called from the main part of the program like so:
quantity = quantityFunction(product)


The return False at the bottom of the code is to do with if product is None, which is needed after a bit of code in another function but has had to go in this function.

If the user input for quantity is a number, all works fine. If it is anything else, the Value Error is printed and you can enter another input. If you put another letter etc in, it repeats again, if you put a number in, it accepts it.

However, it does not return the number you inputted after the letters. It just returns 0.

I suspect this is something to do with how I am repeating the code, i.e. the code should loop back to the start of the function if it hits the Value Error.

Any Ideas?

Answer

You said:

the code should loop back to the start of the function if it hits the Value Error.

Then you should not use return statements, otherwise the function will terminate, returning True or False.