password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password)>8 and len(password)<24:
print("this password is within the given length range")
else:
password=input("Please enter a password within the boundaries: ")
When I run the code and the length of the entered password is more than 8 and 24, it just prints "This password is within the given length range" infinitely. Im not good at coding and im sure ive done something wrong.
You forgot the break
statement to stop the loop. And the loop statement has problems, mainly that you are missing the if
part of the else
.
password=input("Please enter your chosen password within 8 and 24 letters: ")
while True: #will continue until break statement executes
if len(password)>8 and len(password)<24:
print("this password is within the given length range")
break #Quit the loop
else:
password=input("Please enter a password within the boundaries: ")
The above code will run until the user enters a password of 8 < length < 24
.
If you want to continually prompt them for a password you'll need your prompt inside your while loop like this and change the less than and greater than signs around.
password = ""
while len(password) < 8 or len(password) > 24:
password = input("Please enter your chosen password within 8 and 24 letters: ")
The else
only executes after you exit the while
loop using break
(as opposed to when the condition becomes false). You simply want
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password) < 8 or len(password) > 24:
password=input("Please enter a password within the boundaries: ")
If you don't mind using the same prompt for both inputs, use an infinite loop with an explicit break:
while True:
password=input("Please enter your chosen password within 8 and 24 letters: ")
if 8 <= len(password) <= 24:
break
You store a valid password in the 'password' variable. The while loop checks if 'password' is valid, confirms that it is, and it keeps on going. You want your loop to keep on going if the user type an invalid password, rather than a valid one. Try:
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password)<8 or len(password)>24:
password=input("Please enter a password within the boundaries: ")
print("this password is within the given length range")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.