You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现用户选择random/secrets生成密码并解决样本超限报错

问题解决:密码生成器逻辑分支错误及ValueError修复

问题说明

实现了一个支持两种选项的密码生成器:

  • "auth":使用secrets模块生成安全密码
  • "simp":使用random模块生成简单密码
    但存在两个问题:
  1. 无论用户选择哪个选项,两种密码生成逻辑都会被执行
  2. 选择"auth"且输入密码长度为100时,会触发ValueError: Sample larger than population or is negative报错

错误原因

  1. 代码未根据用户选择做分支判断,直接同时执行了secrets.choice和random.sample的生成逻辑
  2. random.sample要求采样的长度不能超过字符池的总数量:你的字符池由26小写+26大写+10数字+8符号组成,总长度为70,当输入长度100时,100>70,触发采样长度超出范围的错误

修复后的完整代码

import string
import secrets
import random

options = ['auth', 'simp']
user_input = ''

msg = "Pick an option:\n"
for index, item in enumerate(options):
    msg += f'{index+1}) {item}\n'

while user_input.lower() not in options:
    user_input = input(msg).lower()

length = int(input('\nEnter the length of password: '))                      
low = string.ascii_lowercase
up = string.ascii_uppercase
num = string.digits
sym = "@#$%&*/?"
all_chars = low + up + num + sym
password = ""

if user_input == 'auth':
    # 使用secrets生成安全密码,允许重复字符,长度无上限(只要内存允许)
    password = ''.join(secrets.choice(all_chars) for _ in range(length))
elif user_input == 'simp':
    # 检查长度是否超过字符池总长度,避免random.sample报错
    if length > len(all_chars):
        print(f"Error: 简单密码长度不能超过{len(all_chars)}(字符池总数量)")
    else:
        # 使用random.sample生成无重复字符的简单密码
        password = "".join(random.sample(all_chars, length))

if password:
    print("\nYour Generated Password is :\n", password)

关键修复点

  • 分支执行逻辑:用if/elif判断用户选择,只执行对应选项的密码生成代码,避免无用逻辑运行
  • 长度校验:给"simp"选项添加长度检查,确保输入长度不超过字符池总长度(70),提前拦截错误
  • 变量赋值修正:将生成的实际密码赋值给password变量,修复原代码中把选项字符串直接作为密码的错误
  • 命名优化:把all改为all_chars,避免和Python内置函数all()冲突

内容的提问来源于stack exchange,提问作者WeeaBOI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:20:34