如何让用户在python中的passowrd程序上退出程序

2024-03-28 23:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我做这个吗。因此,一旦用户猜测3次,整个程序就会关闭,但一旦用户猜错了,就不会让他们退出程序。是的,我知道我又问了同样的问题,但我的问题还没有得到回答,所以请有人帮忙。在

enter image description here

这是我正在尝试的另一个。关于如何退出程序的建议,如果用户通过尝试猜错密码获得了一定的尝试次数。我一直想用系统出口和exit(),但它对我不起作用,所以也许你可以尝试一下,(但请记住我的老师想要它,这样它就可以空闲了)。在

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

Tags: 用户test程序密码inputif系统counter
3条回答

将您的计数器检查转移到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!")
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

您需要将条件counter==3移动到while循环中

也可以这样做

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

一个更好的方法是将这个密码检查打包到一个函数中。在

^{pr2}$

相关问题 更多 >