2017-07-16 138 views
-3

解決下面這樣修復後的代碼,以幫助任何人,如果他們遇到了這個見面...... 原來的問題 - 只有輸入以外的整數過濾掉,而不是整數的範圍1-10之外。條件僅在第一次迭代

lc = "abcdefghijklmnopqrstuvwxyz" #string for lc 
print("------------------------------------------------------------------------------------------------------------------------------------------------------") 

while True: 
    try: 
     passlen = int(input("How many lower case characters would you like in the password? (min 1, max 10) ")) 
     if 1<= passlen<=10: 
        a = "".join(random.sample(lc,passlen)) 
        print("") 


        counter = counter + (passlen) 
        left = 10 - counter 
        nleft = 16 - counter 
        if counter < 10: 
         print("You have used", counter, "characters. You need a minimum of", left, "characters and a maxium of", nleft, "characters to create a password of between 10 and 16 charcters.") 
         print("") 

        elif counter > 16: 
         print("You have used", counter, "charcters, more than the allowed maximum of 16 characters. Please follow the rest of the steps and retry when prompted.") 

        else: 
         print("You have used", counter, "characters, so have met the minimum amount of characters. You have a maximum of", nleft, "characters remaining to create a password with maximum 16 characters.") 
         print("") 

        break 

     else: 
      print("Input must be an integer between 1 and 10, please try again.") 
    except ValueError: 
      print("Input type must be an integer.") 
+0

完全不清楚這段代碼應該做什麼,再加上問題本身並不明顯。 – tadman

+1

您能否提供您的問題[mcve]? –

+2

作爲一個風格問題,「互動」這樣的節目在20世紀80年代去世。編寫一個命令行工具要比'sys.argv'參數好得多,比如你會有一個程序'python passgen.py 20',它會產生一個20個字符的密碼或者如果參數產生錯誤被省略或超出範圍。 – tadman

回答

1

的問題是,當你進入範圍1-10之外的數字,它跳過while循環,你嘗試處理錯誤,特別是while passlen <1 or passlen >10:

爲了解決這個問題,手柄第一while循環內這個邏輯,遠離第二個(省略長打印消息爲了簡潔)的。例如。

while True: 
    try: 
     passlen = int(input("How many lower case characters would you like in the password? (min 1, max 10) ")) 
     if 1 <= pathlen <= 10: 
      break 
     else: 
      print("Input must be an integer between 1 and 10, please try again.") 
    except ValueError: 
     print("Input type not recognized") 
+0

是的。像魅力一樣工作,謝謝。從這裏,我怎麼把這個過濾的輸入帶到while循環之外(到它下面的代碼)呢? – 13odobson

+0

您可以將所有代碼放在您的最後一個else子句中。 – nico

+1

是的,在閱讀你的回覆之前就已經解決了這個問題 - (現在感覺有點傻)tbh重新命令了這樣的反覆,現在通過輸入等改變了迭代感謝你的幫助,欣賞它,因爲我是一個初學者...特別是因爲問題不是很清楚(第一篇文章等)。無論如何程序運行完美。歡呼老闆。 – 13odobson