【问题标题】:Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?Python:如何让程序提示用户一定次数的用户输入?
【发布时间】:2014-11-21 14:11:45
【问题描述】:

在程序中,用户必须输入密码,如果输入错误,程序将再提示他 2 次,如果输入错误,则该程序将过期。我该怎么做。到目前为止,这是我的程序...

password=input("Enter password:")
while password != 'cat': 
    print ("password is wrong, try it again")
    password= input ("Enter your password:")

print ("Password correct be happy")

【问题讨论】:

  • 把它放在一个循环中。如果收到正确的答案,则跳出循环。如果循环在没有正确答案的情况下到期,则执行其他操作。

标签: python python-3.x input passwords prompt


【解决方案1】:

慈善程序员

for trial in range(3):
    print ("Attempt no.",trial, end=" ")
    passw = input('.  Enter password > ')
    if passw == 'cat' : break
else:
    passw = 'cat'

是的,不起眼的for 循环也有一个else 子句:"Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."

【讨论】:

    【解决方案2】:

    试试这个:

    import sys
    max_tries = 3; current_tries = 0
    password=input("Enter password:")
    while password != 'cat': 
        if current_tries > max_tries:
            print "too many tries"
            sys.exit(0)
        print ("password is wrong, try it again")
        password= input ("Enter your password:")
        current_tries +=1
    
    
    print ("Password correct be happy")
    

    【讨论】:

    • 即使用户最后一次尝试正确,这也会给出太多重试消息......相反,您应该将检查放在顶部
    【解决方案3】:
    max_tries = 3
    password = None
    for i in range(max_tries):
        password = input("Enter Password:")
        if password == "cat": break
    if password != "cat": 
        print ("ERROR TOO MANY TRIES!")
    else:
        print ("You Win!")
    

    是一种简单的方法......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      相关资源
      最近更新 更多