重新显示登录提示的最佳方式



我正在编写一个简单的Python(shell)程序,要求输入。 我正在寻找的是字符串的一定长度(len)。 如果字符串不是最小值,我想抛出一个异常并将用户带回输入提示符重试(仅针对给定的尝试次数,例如 3)。

我的代码基本上到目前为止

x=input("some input prompt: ")
if len(x) < 5:
print("error message")
count=count+1 #increase counter

等。。。

-- 这是我卡住的地方,我希望抛出错误,然后回到我的输入......对 Python 来说有点陌生,所以非常感谢帮助。 这将成为Linux机器上脚本的一部分。

循环对此效果很好。

您可能还希望使用raw_input而不是输入。 输入函数以 python 的形式解析和运行输入。我猜您是在要求用户输入各种密码,而不是要运行的python命令。

同样在python中没有i ++,例如使用i += 1。

使用while循环:

count = 0
while count < number_of_tries:
    x=raw_input("some input prompt: ") # note raw_input
    if len(x) < 5:
        print("error message")
        count += 1    #increase counter ### Note the different incrementor
    elif len(x) >= 5:
       break
if count >= number_of_tries:
    # improper login
else:
    # proper login

或带有 for 循环:

for count in range(number_of_tries):
    x=raw_input("some input prompt: ")  # note raw_input
    if len(x) < 5:
        print("error message") # Notice the for loop will
    elif len(x) >= 5:          # increment your count variable *for* you ;)
       break
if count >= number_of_tries-1: # Note the -1, for loops create 
    # improper login           # a number range out of range(n)from 0,n-1
else:
    # proper login

你想要一个while循环而不是你的if,这样你就可以根据需要多次请求另一个输入:

x = input("some input prompt: ")
count = 1
while len(x) < 5 and count < 3:
    print("error message")
    x = input("prompt again: ")
    count += 1 # increase counter
# check if we have an invalid value even after asking repeatedly
if len(x) < 5:
    print("Final error message")
    raise RunTimeError() # or raise ValueError(), or return a sentinel value
# do other stuff with x

最新更新