繁体   English   中英

Python:如何获得一个程序来提示用户一定的固定时间来输入用户信息?

[英]Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?

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

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

print ("Password correct be happy")

慈善程序员

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

是的,谦虚的for循环还具有else子句: “循环语句可能具有else子句;当循环通过用尽列表(带有for)终止循环或当条件变为false(带有while)时执行该语句,但不是当循环由break语句终止时。”

尝试这个:

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

是一种简单的方法...

暂无
暂无

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

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