-2

I'm a beginner to Python and I was fooling around trying to code user input's password. However, I can't get it to loop again if it fails. Please help hahah

import re

p = input("Password: ")
x = True

while x:
    if (len(p)<8 or len(p)>32):
        break
    elif not re.search("[a-z]",p):
        break
    elif not re.search("[0-9]",p):
        break
    elif not re.search("[A-Z]",p):
        break
    elif not re.search("[$#@]",p):
        break
    elif not re.search("\s",p):
        break
    else:
        print("Valid Password")
        x=False
        break
if x:
    print("Not a Valid Password. Please type again.")
    p = input("Password: ")
wyatt
  • 1
  • FIrst of all, use descriptive names for your variables. What is `x` supposed to mean? If you call it `valid_password_entered` your code is more easy to understand. Second of all, why do you only call `input()` once and what is the `while` loop supposed to do? – wovano Nov 23 '21 at 12:02
  • 3
    What do you think `break` does? – bereal Nov 23 '21 at 12:03
  • Also, indentation is important in Python. – wovano Nov 23 '21 at 12:03
  • A `break` will break from the loop always. You can use `continue` if you want to resume. Please read and learn more about looping and branching! – Kris Nov 23 '21 at 12:03

1 Answers1

0

You have a while loop. That will keep running until the condition is false. So you want to prompt for the password inside that loop, at the start. Then you run through your tests, and only if they all pass, you should break out of the loop.

However, if any test fails you don't want to break from the loop - you want to restart it from the top, prompting for a new password. The keyword to do this is continue, not break.

Pines
  • 396
  • 1
  • 8