Python随机密码生成器运行返回空白结果问题求助
错误原因
- 核心问题出在for循环的逻辑:
characters[random.randint(0, 2)]会随机取出字母、符号、数字中的一整个列表,后续遍历这个列表得到的char是单个字符,你拿整个letters/symbols/numbers列表和单个字符判等,条件永远不成立,密码变量不会拼接任何内容,所以输出为空白。 - 次要问题:计数判断用
<=会导致实际生成的字符数超出输入的要求,应该用<;原代码中存在多余的首行缩进、HTML转义字符(比如&、")也会影响运行。
修正后的完整代码
import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] print("欢迎使用PyPassword密码生成器!") nr_letters= int(input("请输入密码中需要包含的字母数量:\n")) nr_symbols = int(input("请输入密码中需要包含的符号数量:\n")) nr_numbers = int(input("请输入密码中需要包含的数字数量:\n")) total_len = nr_letters + nr_symbols + nr_numbers password = "" letter_count = 0 symbol_count = 0 number_count = 0 while len(password) < total_len: # 每次随机选择字符类型:0=字母,1=符号,2=数字 char_type = random.randint(0, 2) if char_type == 0 and letter_count < nr_letters: password += random.choice(letters) letter_count += 1 elif char_type == 1 and symbol_count < nr_symbols: password += random.choice(symbols) symbol_count += 1 elif char_type == 2 and number_count < nr_numbers: password += random.choice(numbers) number_count += 1 print("生成的密码为:", password)
修改说明
- 把原来错误的遍历逻辑替换为while循环,只要密码长度没达到总要求就持续生成字符
- 每次随机选择字符类型,再对应判断该类型的剩余生成额度,额度足够才添加对应字符
- 用
random.choice()替代手动计算索引取元素的写法,更简洁也不容易出错 - 修复了原代码中的多余缩进、HTML转义字符问题,交互提示已汉化
内容的提问来源于stack exchange,提问作者Sftwr-crativ
相关产品推荐
相关产品推荐

