2017-04-24 75 views
2
users = {'adam' : 'Test123', 'alice' : 'Test321'} 
status = "" 
status = input("If you have an account, type YES, NO to create a new user, QUIT to exit: ") 

while status != 'QUIT': 

    if status == "YES": 
     u_name = input("Please provide your username: ") 
     u_pwd = input("Please provide your password: ") 

     if users.get(u_name) == u_pwd: 
      print("Access granted!") 
      break 

     else: 
      print("User doesn't exist or password error! You have 2 more attempts!") 

    elif status == "NO": 
     print("\nYou're about to create a new user on my very first app. Thank you!") 
     new_u_name = input("Please select a name for your account!") 
     new_u_pwd = input("Please select a password for your account!") 
     users[new_u_name] = new_u_pwd 
     print("Thank you " + new_u_name + " for taking the risk.") 

    elif status == "QUIT": 
     print("Smart choice lol. Please come back in few months") 

什麼是執行按照以往方式: - 如果用戶選擇Yes,並提供有效的用戶名密碼+ =准許進入退出循環(我用break在這種情況下) - 我將如何實現一個循環,以便在第一個else語句後,用戶將被要求再次輸入用戶名和密碼,但只有另外2次嘗試?蟒蛇用戶名和密碼限制驗證爲x試圖

回答

1

我想你可以創建一個計數器,是這樣的:

users = {'adam' : 'Test123', 'alice' : 'Test321'} 
status = "" 
status = input("If you have an account, type YES, NO to create a new user, QUIT to exit: ") 
max_attempts = 2 
while status != 'QUIT': 

    if status == "YES": 
     u_name = input("Please provide your username: ") 
     u_pwd = input("Please provide your password: ") 

     if users.get(u_name) == u_pwd: 
      print("Access granted!") 
      break 

     else: 
      if max_attempts > 0: 
       print("User doesn't exist or password error! You have {} more attempts!".format(max_attempts)) 
       max_attempts -= 1 
      else: 
       print("Too many wrong passwords. Bye!") 
       break 

    elif status == "NO": 
     print("\nYou're about to create a new user on my very first app. Thank you!") 
     new_u_name = input("Please select a name for your account!") 
     new_u_pwd = input("Please select a password for your account!") 
     users[new_u_name] = new_u_pwd 
     print("Thank you " + new_u_name + " for taking the risk.") 

    elif status == "QUIT": 
     print("Smart choice lol. Please come back in few months") 

注意

您可能還需要實現以下功能:

1 - 檢查如果用戶名在提示輸入密碼前退出。
2 - 使YESNO情況InsEnsiTive。

+0

謝謝佩德羅,請爲我遲到的迴應道歉!它的功能就像是一種魅力:)但是,有一個問題,請問你是怎麼設法增加打印信息的嘗試次數的? – adam86

+0

非常歡迎@ adam86。如果我的答案對您有幫助,請考慮投票1 +▲,並通過在投票箭頭中間點擊複選標記✔接受它作爲正確答案,tks! –