条件仅在第一次迭代中得到满足

时间:2017-07-16 21:27:39

标签: python

如果他们偶然发现这个问题,解决了下面的补救代码,以帮助任何人... 原始问题 - 仅过滤掉整数以外的输入,而不是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.")

1 个答案:

答案 0 :(得分:1)

问题是当您输入1-10范围之外的数字时,它会跳过您尝试处理错误的while循环,特别是while passlen <1 or passlen >10:

要解决此问题,请在第一个while循环内处理此逻辑并删除第二个逻辑(为简洁起见省略长打印消息)。 E.g。

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