如何从else语句重新启动代码?

时间:2019-05-20 08:36:33

标签: python python-3.x if-statement

这里有一些我正在处理的代码(Python 3.4),并且我不知道如何在else语句之后使程序重新启动。我知道没有goto声明。

我试图通过将if语句放在while true循环中来弄乱,但它只是循环了print行并一遍又一遍地打印输出

import random
    import string

    PassGen = ""

    length = int(input("how many characters would you like your password to have 8-15? "))

    if 8 <= length <=15:
        while len(PassGen) != length:
            Num1 = random.choice(string.ascii_uppercase)
            Num2 = random.choice(string.ascii_lowercase)
            Num3 = random.choice(string.digits)
            everything = [Num1, Num2, Num3]
            PassGen += random.choice(everything)
        print (PassGen)
    else:
        print ("that is an incorrect value")

目前,通过从用户处获取输入内容,然后查看输入内容是否在 8-15 之间,它可以正常工作。如果是这样,它将使用内部while循环生成一个密码。否则,它将输出错误的值。

1 个答案:

答案 0 :(得分:1)

你很近。 while True很好,但是您还需要一个break才能摆脱困境:

while True:
    length = int(input("how many characters would you like in your password"))
    if 8 <= length <=15:
        while len(PassGen) != length:
            Num1 = random.choice(string.ascii_uppercase)
            Num2 = random.choice(string.ascii_lowercase)
            Num3 = random.choice(string.digits)
            everything = [Num1, Num2, Num3]
            PassGen += random.choice(everything)
        print (PassGen)
        break
    else:
        print ("that is an incorrect value")