Nathan Shoesmith Nathan Shoesmith - 5 months ago 9
Python Question

Incorrect Looping and returning of variable

My code below is checking if the input (quantity) is a number. If it is a number first time, it returns the number fine. However, if you were to put a letter in, and then when the function loops enter a number, '0' is returned rather than the number you inputted.

def quantityFunction():
valid = False
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:
try:
int(i)
return int(quantity)
except ValueError:
print("We didn't recognise that number. Please try again.")
quantityFunction()
return False


Am I looping the function incorrectly?

Answer

You function is not correct actually, you are using while loop together with a recursion function, which is not necessary in this case.

While, You could try the following code, which is a bit modification based on your function but use only while loop.

def quantityFunction():
    valid = False
    while not valid:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        for i in quantity:
            try:
                int(i)
                return int(quantity)
            except ValueError:
                print("We didn't recognise that number. Please try again.")
                valid = False
                break

Though, actually you could have done this in a easier way, if you wish to use while loop:

def quantityFunction():
    while True:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        if quantity.isdigit():
            return int(quantity)
        else:
            print("We didn't recognise that number. Please try again.")

And if you really want to use recursive function, try following:

def quantityFunction1():
    quantity = input("Please enter the amount of this item you would like to purchase: ")
    if quantity.isdigit():
        return int(quantity)
    else:
        print("We didn't recognise that number. Please try again.")
        return quantityFunction()

Please note if you want the value to be returned eventually when you type in a number, you need to use return quantityFunction() in the else. Otherwise eventually nothing will be returned. This also explains your question of why you input a number at the first time you could return it but not afterwards.