2017-06-05 34 views
-1

我在菜單系統的某些代碼中遇到了一些問題。到目前爲止,我沒有完成但我遇到了問題。它可以和account.leeman一起工​​作,但我永遠不會得到'管理員'的工作,它總是回滾到開始。我已經看了一段時間的代碼,但我無法弄清楚爲什麼這是爲什麼它永遠不會繼續。 「添加」的部分代碼可以忽略不計,因爲它不是一個問題還沒有,但如果你能改善它看到任何方式,請讓我知道Python 3中的循環

所以這是我:

usernames=["m.leeman","administrator"] 
passwords=["pA55w0rd","password"] 
while True: 
    count=0 
    add_or_enter=input("Would you like to Enter a username or Add a new one?: ").lower() 
    if add_or_enter=="enter": 
     username=input("Please enter username: ") 
     while (count+1)!=(len(usernames)): 
      #problem somewhere here 
      if username==usernames[count]: 
       print("Username accepted") 
       password=input("Please enter password: ") 
       if password==passwords[count]: 
        print("Welcome "+str(username)) 
        print("Continue here") 
       else: 
        print("Incorrect password") 
      else: 
       count+=1 
       if count==len(usernames): 
        print("User does not exit") 
       else: 
        () 
        #should run again after this 
    elif add_or_enter=="add": 
     new_user=input("Enter a new username: ") 
     if (new_user=="add") or (new_user==usernames[count]): 
      print("Username unavailiable") 
     else: 
      count=+1 
      if count==len(usernames)-1: 
       usernames.append(new_user) 
       new_password=input("Enter a password for this user: ") 
       passwords.append(new_password) 
       print("User "+new_user+" successfully created") 

任何回覆將非常有幫助。謝謝。

+0

什麼是理想的行爲? – roganjosh

+0

假設,如果你做'while count!= len(username):'會發生什麼? – Kevin

+0

似乎在用戶輸入中可能存在一些來自'raw_input''用戶名'和''m.leeman \ n「'的隱藏換行符,在你指出''#problem某處在''之後'的行後,嘗試'if username.strip()==用戶名[count] .strip():'清理字符串並剝離換行符。工作時,我試了一下。 – davedwards

回答

0

你永遠不會得到管理員,因爲你是雙倍遞增計數。你有計數增加的條件,然後在else語句中,當它不= m.leeman所以在else語句後取出計數+ = 1。

1

讓我們看看在這行代碼:

while (count+1)!=(len(usernames)): 

在第一循環中,計數爲0,因此0 + 1 = 2和循環執行!。他們輸入的名字「administrator」不匹配「m.leeman」,所以count增加1,循環將再次執行。

這一次,count = 1。所以count + 1 = 2,這恰好是用戶名的長度。該循環不執行並且未找到管理員帳戶。

解決方案?拆下+ 1

while count != len(usernames): 

希望這有助於