Home > Enterprise >  While Loop help. Running loop twice
While Loop help. Running loop twice

Time:09-07

I am trying to code a simple random word generator and I am having issues with the while loop. When I run the code it asks the user for a strong or weak password. Strong will generate 14 random characters and weak will combine two words from a list. After choosing a password it will ask if you another password and if yes it will ask the question again. But when I run it once it asks for another password but it asks choose a strong/weak 2 times instead of asking for another password.

def randpasswd(length, chars=None):
    if chars == None:
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%¨&*()_ /*\\|<>;:"

        password = ""
        for i in range(length):
            password  = random.choice(chars)
    return password
def choosing():
    choose = input("Choose strong or weak password: ")
    a = ["password", "crash", "intel", "working"]

    if choose == "strong":
        print(randpasswd(14))
    if choose == "weak":
        print(''.join(random.choices(a, k=2)))
while True:
    choosing()
    done = input("Do you want another password? ")
    if done == "yes":
        choosing()
    elif done == "no":
        print("password is set")
        break

CodePudding user response:

Replace

if done == "yes":
    choosing()

with

if done == "yes":
    continue

so instead of

  1. choosing() being run,
  2. followed by the elif branch that would not be taken (since the other branch was taken),
  3. followed by the loop starting over,

control just skips back to the start of the while True loop, where choosing() will be run anyway. (pass would do here too instead of continue, but the latter is more explicit.)

CodePudding user response:

Replace your current while loop with this:

want_another = "yes"
while want_another != "no":
    if want_another == "yes":
        choosing()
    want_another = input("Do you want another password? ")
print("password is set")

Right now, done is very badly named, since done is "no" when you are done and "yes" when you are not done.

  • Related