请有人试着帮我解决这个问题。因此,一旦用户猜到整个程序关闭3次,但一旦用户弄错了,它就不会让他们退出程序。是的,我知道我再次提出同样的问题,但我还没有回答我的问题,所以请有人帮忙。
这是另一个我尝试过的人。如果用户通过尝试猜测密码错误而获得一定数量的尝试,则有关如何退出程序的任何建议。我一直在尝试使用sys.exit和exit(),但它还没有为我工作,所以也许你可以尝试一下,(但请记住我的老师想要它,以便 IDLE )。
Counter=1
Password=("Test")
Password=input("Enter Password: ")
if Password == "Test":
print("Successful Login")
while Password != "Test":
Password=input("Enter Password: ")
Counter=Counter+1
if Counter == 3:
print("Locked Out: ")
break
答案 0 :(得分:0)
counter = 1
password = input("Enter password: ")
while True:
if counter == 3:
print("Locked out")
exit()
elif password == "Test":
print("That is the correct password!")
break
else:
password = input("Wrong password, try again: ")
counter += 1
答案 1 :(得分:0)
您需要在while循环中移动条件counter==3
这也可以这种方式完成
import sys
password = input("Enter password : ")
for __ in range(2): # loop thrice
if (password=="Test"):
break #user has enterd correct password so break
password = input("Incorrect, try again : ")
else:
print ("Locked out")
sys.exit(1)
#You can put your normal code that is supposed to be
# executed after the correct password is entered
print ("Correct password is entered :)")
#Do whatever you want here
更好的方法是将此密码检查事物包装到函数中。
import sys
def checkPassword():
password = input("Enter password : ")
for __ in range(2):
if (password=="Test"):
return True
password = input("Incorrect, try again : ")
else:
print ("Locked out")
return False
if (checkPassword()):
#continue doing you main thing
print ("Correct password entered successfully")
答案 2 :(得分:0)
将计数器检查移至while循环。
还可以使用getpass在python中输入密码:)
import sys
import getpass
counter = 1
password = getpass.getpass("Enter Password: ")
while password != "Test":
counter = counter + 1
password = getpass.getpass("Incorrect, try again: ")
if counter == 3:
print("Locked Out")
sys.exit(1)
print("Logged on!")