2016-12-05 50 views
-2

有人可以試着幫我做這個,請。因此,一旦用戶猜測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你可以給我修正後的版本的截圖請非常感謝 –

回答

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

謝謝你的迴應。我的老師說,他想要一些東西,以便「實際」關閉程序,這是迫使用戶獲得程序的最接近的方式,還是不是?我聽說過:sys.exit(1) –

+0

exit()與sys.exit()幾乎相同() 如果您希望程序返回錯誤代碼 – TheClonerx

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

,則可以將exit(1) 。但是有沒有什麼需要填寫的地方是否可以加上下劃線(我是一個noobie抱歉),但它也會關閉程序,除了空白之外的任何原因。 –

+0

@AmirBreakableTv沒有什麼填充那裏,這是如何在python中使用for循環,如果不需要該變量,則使用__'(雙下劃線)。如果您在三次嘗試中未正確輸入密碼,則會關閉(如您所願)。如果輸入正確,您可以添加其他需要在最後一個'else'塊之後執行的語句。我會編輯我的答案。 –

+0

@Grupad Mamadapur謝謝 –

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

謝謝我會嘗試。 –

+0

它說:警告(來自警告模塊):第101行 return fallback_getpass(提示,流) GetPassWarning:無法控制終端上的回顯。 警告:可能會回顯密碼輸入。 –

+0

這是因爲您正在使用IDLE編輯器,http://stackoverflow.com/questions/17520292/is-there-easy-way-to-prevent-echo-from-input。您的標記不會使用IDLE來標記我的設定,而我對您的建議是您不使用IDLE;) – shash678

相關問題