首页 > 解决方案 > 如果输入不符合 for 循环的要求,如何强制用户重新输入?

问题描述

这是我的代码,要求用户输入他们想要生成的密码字符数。如果他们输入数字 < 8,我想强制他们重新输入。否则,将生成密码。但我被 for 循环卡住了,因为它产生了无限期的打印。

任何帮助,将不胜感激。

import string
import random

lower_string = string.ascii_lowercase
upper_string = string.ascii_uppercase
special_string = "!@#$%&*()[]{}"
number = '0123456789'

list_string = [lower_string, upper_string, special_string, number]

password = ''

password_length = int(input("Enter length of password: "))


while password_length < 8:
    print("Hey, this password's length is not good. Enter > 8")
    continue
else:
    for _ in range(password_length):
        x = random.choice(random.choice(list_string)) 
        password = password + x
print(password)

标签: pythonpython-3.xwhile-loop

解决方案


尝试将input语句放在 while 循环中

while True:
    password_length = int(input("Enter length of password: "))
    if password_length < 8:
        print("Hey, this password's length is not good. Enter > 8")
    else:
        break

推荐阅读