python - 限制 python 3 中的无效输入

标签 python python-3.x syntax

我需要限制允许的无效输入的数量,以便在给定的尝试次数后程序退出。

输入小于零定义为无效。

假设尝试次数为 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()

我如何限制无效输入尝试的次数并使代码能够返回再次询问问题并提示输入但仍然跟踪以前的尝试?

最佳答案

您必须使用循环,在这种情况下,while 循环会很方便。您必须声明一个变量 invalid_attempts 来记录用户提供的无效输入的次数。

完成循环的条件是当 invalid_attempts 大于或等于 3 时,它会在您获得无效输入时增加。您可能需要更改 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

注意:因为 number 是方法的名称,所以你不应该在内部调用一个同名的变量(因为如果你这样做,你就不会能够在内部使用该函数,如果有必要的话),在这种情况下,我正在调用方法 get_input

关于python - 限制 python 3 中的无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22274766/

相关文章:

python - 与 sleep 命令相比,使用循环在 python 中等待更多 CPU 密集型?

python - 无法加载 native TensorFlow 运行时。 python 3.5.2

python - 在Python命令中添加管道符号

Haskell 并行和广义(类 SQL)列表理解问题

python - Django 不允许创建项目

python - 我在执行 multivariate_gauss pdf 时遇到什么问题?

python - 使用子进程从python执行ffmpeg命令

python - 你能覆盖一个由函数结果定义的变量而不先在 python 中清除吗?

java - 尝试按特定顺序将一维数组放入二维数组

bash - Bash 中的 "[0: command not found"