简体   繁体   中英

limiting invalid input in python 3

I need to limit the number of invalid inputs allowed so that after the given amount of tries the program exits.

Invalid is defined by the input being less than zero.

The number of attempts let say is 3.

def number():        
    number = float(input('please enter a number (must be greater thatn zero): '))

    if number >= 0 :    
        print ('you choose number:', number)    
    else:
        print ('invalid input')    
        return 

number()

How would I limit the number of invalid input attempts and make it so that the code would return to asking the question again and prompt for input but still keep track of previous attempts?

You have to use a loop , in this case a while loop will be convinient. You have to declare a variable invalid_attempts to keep the count of how many invalid inputs the user has given.

The condition to finish the loop will be when invalid_attempts , which is increased when you get an invalid input, is greater or equal to 3 . You may want to change 3 to fit your requirements:

def get_input():
    invalid_attempts = 0

    while invalid_attempts < 3:
        number = float(input('please enter a number (must be greater thatn zero): '))

        if number >= 0 :
            print ('you choose number:', number)
            return number # so you can call the method as 'some_variable = get_input()'
        else:
            print ('invalid input')
            invalid_attempts += 1

Note: Since number is the name of the method, you shouldn't call a variable inside with the same name (because if you do, you won't be able to use that function inside, if it's necessary), in this case I'm calling the method get_input .

Use whilie loop before number = ..., for instance:

count = 0
while count < 3:
    # do rest of the stuffs
    count += 1

You can also do it slightly more elegantly using recursion:

def get_number(max_tries, count = 0)
    if count < max_tries:
       valid_input = False
       number      = 0
       try:
           number = float(input('Please enter a number > 0'))
           if number > 0:
              valid_input = True
       except:
           pass
       if valid_input:
          return number
       else:
          return get_numbers(max_tries, count+1)
    else:
       print('Sorry, Too many Tries!)
       return None

Whether you use a while loop or recursion is usually a matter of taste. They're functionally equivalent in many situations, of which this is on. This example also accounts for what happens if the user enters something that isn't a number, which will cause the float cast to throw.

Update: To clarify a question asked by the OP:

def get_numbers(max_tries, count = 0)

Defines a function get_numbers , which takes two inputs, max_tries and count . count is given a default value, count = 0 , which means if you call the function without specifying the count parameter, it will automatically assign it to be 0 . max_tries is left without a default value, meaning you need to specify it every time you call the function or python will throw an error. If you usually have the same number of maximum tries, you could also assign this a default value, which would allow you to simply do number = get_numbers() and have it work as expected.

Recursion , to over-simplify, is basically when a function calls itself during its execution. Let's assume we did the following:

 number = get_number(10)

And the user enters -1, which will cause the code to reach:

 else:
     return get_numbers(max_tries, count+1)

Since we said get_numbers(10) , max_tries = 10 , and count = 0 , so this line becomes:

 else:
    return get_numbers(10, 1)

This causes the function to return the result of calling get_numbers again. Eventually the user will either enter valid input, or count > max_tries , which will cause the function to finally return a value.

Read the wiki I liked to, recursion is hard to explain without drawing it, but hopefully that helps.

Actually, I think a for loop looks nicer:

for retry in range(5): # number of retries
    try:
        choice = float(input('please enter a number (must be greater thatn zero): '))
    except ValueError:
        print('Please enter an actual number')
        continue
    if choice >= 0:
        print('You chose ', choice)
        break
    else:
        print('Number must be >= 0')
        continue
else:
    print('Too many failures: be more cooperative')

(This is called a for-else construct; the else runs only if the for loop did not break ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM