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

问题描述:

有人可以试着帮我做这个,请。因此,一旦用户猜测3次,整个程序关闭,但一旦用户出错,它不会让他们退出程序。是的,我知道我再次问同样的问题,但我还没有得到我的问题,所以请有人帮忙。如何让用户在python的passowrd程序中退出程序

enter image description here

这里有另外一个我想出去。任何有关如何通过尝试猜错密码来尝试退出程序的建议。我一直在尝试使用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 
+2

请复制代码在您的文章的文字,而不是图像中 –

+1

移动计数器检查进入循环 –

+0

@JosephYoung你可以给我修正后的版本的截图请非常感谢 –

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 
+0

谢谢你的回应。我的老师说,他想要一些东西,以便“实际”关闭程序,这是迫使用户获得程序的最接近的方式,还是不是?我听说过:sys.exit(1) –

+0

exit()与sys.exit()几乎相同() 如果您希望程序返回错误代码 – TheClonerx

你需要移动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") 
+0

,则可以将exit(1) 。但是有没有什么需要填写的地方是否可以加上下划线(我是一个noobie抱歉),但它也会关闭程序,除了空白之外的任何原因。 –

+0

@AmirBreakableTv没有什么填充那里,这是如何在python中使用for循环,如果不需要该变量,则使用__'(双下划线)。如果您在三次尝试中未正确输入密码,则会关闭(如您所愿)。如果输入正确,您可以添加其他需要在最后一个'else'块之后执行的语句。我会编辑我的答案。 –

+0

@Grupad Mamadapur谢谢 –

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

谢谢我会尝试。 –

+0

它说:警告(来自警告模块):第101行 return fallback_getpass(提示,流) GetPassWarning:无法控制终端上的回显。 警告:可能会回显密码输入。 –

+0

这是因为您正在使用IDLE编辑器,http://*.com/questions/17520292/is-there-easy-way-to-prevent-echo-from-input。您的标记不会使用IDLE来标记我的设定,而我对您的建议是您不使用IDLE;) – shash678