python - 如果输入不符合 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)
解决方案
尝试将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
推荐阅读
- embedded - 在 STM32 设备中读取和写入文件到闪存的末尾
- clojure - 如何遍历列表并制作元素列表
- asp.net-core - Blazor 服务器端递归组件内存消耗过多
- javascript - Chrome 扩展将动态脚本注入标头和打开正文标记后
- d3.js - 气泡图中 y 位置的强制碰撞
- xcode - Xcode 11 - 关于为 iOS 构建的 ld 警告,但为独立构建的目标文件
- c++ - 将 Eigen::MatrixXd 转换为 arma::mat 并在新对象上制作副本
- c++ - 做图灵机,不太懂动作表
- apache - Python 应用程序的 HTTP 504 错误 AWS ElasticBeanstalk
- javascript - React Hooks 静态变量:对象属性与 useRef()