2015-10-08 103 views
0

我正在編寫一個程序,要求用戶輸入密碼。如果密碼與我設置的常量相匹配,則會打印出「已成功登錄的消息」。但是,如果密碼不正確,則會提供剩餘猜測次數,並要求用戶再次嘗試。該程序應該在3次錯誤猜測後結束,但即使經過3次嘗試後仍會繼續詢問。我認爲問題出在我的while循環中,但我不確定。我如何修復我的while循環

代碼:

def main(): 
    PASSWORD = "apple" 
    ALLOWED = 3 

    password = input("Enter the password: ") 
    while password != PASSWORD : 
     ALLOWED = ALLOWED - 1 
     print("Wrong. You have", ALLOWED, "guesses left") 

     if ALLOWED == 0: 
        print("You have been locked out") 
     password = input("Enter again ")    


    print("You have successfully logged into the system") 



main() 
+2

你不破環了似乎輕鬆了不同版本時沒有可嘗試離開 – leeor

+0

另外,代替使用'raw_input' 'input' – zengr

+1

@zengr也許它是Python 3 – Darcinon

回答

0

條件密碼= PASSWORD是不夠的,退出循環(如果只有給出正確的密碼,這將退出循環)。在同時添加條件(密碼!=密碼,允許> 0)

3

現在你永遠不會退出你的while循環。要突破它,請使用break關鍵字。 要完全退出程序,您需要import syssys.exit() 我建議將這些添加到您的if ALLOWED == 0聲明中。

1

您需要使用break才能退出循環,或者添加輔助條件,否則無論如何它都會繼續運行,直到密碼正確。

所以,要麼:

while (password != PASSWORD) and (ALLOWED > 0): 

或者:

if ALLOWED == 0: 
       print("You have been locked out") 
       break 
+0

'break out或添加測試仍然會顯示「您已登錄」,因爲循環後面的下一行顯示「您已成功登錄系統「'。您需要退出該功能,而不僅僅是循環。 – ShadowRanger

+0

啊,那是真的。除了解決眼前的問題之外,我並沒有真正關注這些問題。我的錯。 – Llamageddon

0

變化print("You have been locked out")sys.exit("You have been locked out")(或以其他方式退出main)。請記住import sys使用sys.exit

0

您的while循環需要輸入正確的密碼才能完成,並且沒有其他方式可以退出循環。我建議一個突破聲明:

def main(): 
    PASSWORD = "apple" 
    ALLOWED = 3 

    password = input("Enter the password: ") 
    while password != PASSWORD : 
     ALLOWED = ALLOWED - 1 
     print("Wrong. You have", ALLOWED, "guesses left") 

     if ALLOWED == 0: 
      print("You have been locked out") 
      break 
     password = input("Enter again ") 

    print("You have successfully logged into the system") 

如果您的程序需要安全,您可能需要做更多的研究。

0

管理使其工作,但只是讓它檢查,如果允許== 0,如果它打印「你被鎖定」,如果允許< = 0,那麼它不會讓你走得更遠。

def main(): 
    PASSWORD = "apple" 
    ALLOWED = 3 

    password = input("Enter the password: ") 
    while password != PASSWORD or ALLOWED <= 0: 
     ALLOWED = ALLOWED - 1 
     if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left") 
     if ALLOWED == 0: print("You have been locked out") 
     if ALLOWED < 0: 
        print("You have been locked out") 
     password = input("Enter again ")    


    print("You have successfully logged into the system") 



main() 

也寫這在我看來

def main(): 

    USERNAME = "admin" 
    PASSWORD = "root" 
    ATTEMPTS = 3 
    while ATTEMPTS >= 1: 
     print("You have",ATTEMPTS,"attempts left") 
     if ATTEMPTS == 0: 
      break 
     user = input("Please enter your username:") 
     password = input("Now enter your password:") 
     if user == USERNAME and password == PASSWORD: 
      print("\nYou have successfully logged into the system") 
      return 
     else: 
      print("\nThis user name or password does not exist\n") 
      ATTEMPTS -= 1 
    print("you have been locked out.") 

main()