简体   繁体   English

限制python 3中的无效输入

[英]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. 可以说的尝试次数为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. 您必须使用循环 ,在这种情况下, while循环将很方便。 You have to declare a variable invalid_attempts to keep the count of how many invalid inputs the user has given. 您必须声明一个变量invalid_attempts以保持用户给定的无效输入的数量。

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 . 完成循环的条件将是当invalid_attempts大于或等于3时,它会在获得无效输入时增加。 You may want to change 3 to fit your requirements: 您可能需要更改3以适合您的要求:

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 . 注意:由于number是方法的名称,因此您不应在内部使用相同的名称调用变量(因为如果这样做,则在必要时将无法在内部使用该函数),在这种情况下,正在调用方法get_input

Use whilie loop before number = ..., for instance: 在数字= ...之前使用whilie循环,例如:

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. 是否使用while循环或递归通常取决于您的口味。 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. 此示例还说明了如果用户输入的数字不是数字会发生什么,这将导致float转换抛出。

Update: To clarify a question asked by the OP: 更新:要澄清OP提出的问题:

def get_numbers(max_tries, count = 0)

Defines a function get_numbers , which takes two inputs, max_tries and count . 定义一个函数get_numbers ,该函数接受两个输入max_triescount 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 . count被赋予默认值count = 0 ,这意味着如果您在不指定count参数的情况下调用该函数,它将自动将其分配为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. max_tries没有默认值,这意味着您每次调用函数时都需要指定它,否则python会抛出错误。 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. 如果通常具有相同的最大尝试次数,则还可以为其指定一个默认值,这将使您可以简单地执行number = get_numbers()并使它按预期工作。

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: 然后用户输入-1,这将导致代码达到:

 else:
     return get_numbers(max_tries, count+1)

Since we said get_numbers(10) , max_tries = 10 , and count = 0 , so this line becomes: 由于我们说过get_numbers(10)max_tries = 10count = 0 ,所以这一行变成:

 else:
    return get_numbers(10, 1)

This causes the function to return the result of calling get_numbers again. 这将导致函数再次返回调用get_numbers的结果。 Eventually the user will either enter valid input, or count > max_tries , which will cause the function to finally return a value. 最终,用户将输入有效输入,或者count > max_tries ,这将导致该函数最终返回一个值。

Read the wiki I liked to, recursion is hard to explain without drawing it, but hopefully that helps. 阅读我喜欢的Wiki,如果不绘制递归就很难解释,但是希望可以有所帮助。

Actually, I think a for loop looks nicer: 实际上,我认为for循环看起来更好:

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 ). (这称为for-else构造; else仅在for循环未break )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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