user6275319
user6275319

Reputation:

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?

Upvotes: 2

Views: 125

Answers (5)

Aniket Pawar
Aniket Pawar

Reputation: 2721

You should try this..

def quantityFunction(product):
    valid = False
    while True:
       if product is not None:
          quantity = raw_input("Please enter the amount of this item you would like to purchase: ")

          if quantity.isdigit():
             return int(quantity)
             valid = True
          else:
             print("We didn't recognise that number. Please try again.")
             continue

       return False

quantity = quantityFunction("myproduct")

Upvotes: 0

Prune
Prune

Reputation: 77837

First, let's address the code. Simply stated, you want a function that will loop until the user enters a legal quantity.

product doesn't do much for the function; check it in the calling program, not here. Let the function have a single purpose: fetch a valid quantity.

Let's work from there in the standard recipe for "loop until good input". Very simply, it looks like:

Get first input
Until input is valid
... print warning message and get a new value.

In code, it looks like this.

def get_quantity():
    quantity_str = input("Please enter the amount of this item you would like to purchase: ")

    while not quantity_str.isdigit():
        print("We didn't recognise that number. Please try again.")
        quantity_str = input("Please enter the amount of this item you would like to purchase: ")

    return quantity

As for coding practice ...

Develop incrementally: write a few lines of code to add one feature to what you have. Debug that. Get it working before you add more.

Learn your language features. In the code you've posted, you misuse for, in, return, and a function call.

Look up how to solve simple problems. try/except is a more difficult concept to handle than the simple isdigit.

Upvotes: 0

Ben
Ben

Reputation: 1581

Try this (some formatting included too, but the functionality should be the same):

def determine_quantity(product):  # descriptive function name
    if not product:  # avoiding nesting
         return False
    while True:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        try:
            return int(quantity)  # try to convert quantity straight away
        except ValueError:
            print("We didn't recognise that number. Please try again.")
            # nothing here means we simply continue in the while loop

Ideally, you'd take product out. A function should do as little as possible, and this check is better off somewhere else.

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

Upvotes: 0

gaganso
gaganso

Reputation: 3011

Few issue:

1) return statement returns control to the calling function.

2) You are looping over the input, which is wrong.

3) valid=True isn't executed at all.

def quantityFunction(product):
    valid = False
    while True:
        if product is not None:
            quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
            try:
                    return int(quantity)
                    #valid = True (since it is never run)
            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

quantityFunction("val")

Note : Use raw_input() in case of Python 2.7 and input() in case of 3.x

Upvotes: 2

heltonbiker
heltonbiker

Reputation: 27575

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.

Upvotes: 2

Related Questions