0

Here I have some code I've been working on (Python 3.4) and I can't figure out how to get the program to restart after the else statement. I know that there is no goto statement.

I have tried messing about by putting the if statement in a while true loop but it just looped the print line and printed the output over and over again

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

At the moment it works perfectly fine by taking an input from the user then seeing if the input is between 8-15. If so, it makes a password with the inner while loop. Otherwise, it prints the incorrect value.

gmds
  • 19,325
  • 4
  • 32
  • 58
  • you can use `While true:` loop and `break` out of the loop from `if and else statement` as needed. – justjais May 20 '19 at 08:43
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Matthias May 20 '19 at 09:09

1 Answers1

1

You were close. while True is fine, but you also need a break to get out of it:

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")
gmds
  • 19,325
  • 4
  • 32
  • 58