Python:如何让程序提示用户输入一定数量的固定时间?

时间:2014-11-21 14:11:45

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

在程序中,用户必须输入密码,如果他输入错误,程序将再次提示他2次,如果他没有正确,那么程序将会过期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")

3 个答案:

答案 0 :(得分: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."

答案 1 :(得分:0)

试试这个:

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")

答案 2 :(得分:0)

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!")

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