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

使用Python random.sample()时出现TypeError错误求助

解决密码生成器的TypeError问题

错误原因

你遇到的TypeError: '<=' not supported between instances of 'int' and 'type',根源在这行代码:

password = random.sample(charaters, range)

这里的range是Python的内置类型,不是用户输入的密码长度值。random.sample()的第二个参数要求传入整数,但你传了一个类型,导致内部比较时出现类型不匹配的错误。

修复方案

  1. 替换错误参数:把range换成用户输入的user_input,这才是你需要的密码长度。
  2. 优化输入验证逻辑:不用手动列出1-50的所有数字,直接用范围判断1 <= user_input <=50,代码更简洁易维护。
  3. 转换密码格式:random.sample()返回的是字符列表,用''.join()把它拼接成字符串,输出正常的密码格式。
  4. 修正拼写错误:原代码里的charaters是拼写错误,改为characters避免潜在问题。

修正后的完整代码

import random

characters = ["1","2","3","4","5","6","7","8","9","0", 
              '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', 
              "!", "@", "?","#", "$", "*"]

def Randomize():
    while True:
        user_input = int(input("Select the password range (1-50): "))
        
        # 优化输入验证
        while not 1 <= user_input <= 50:
            print("Please select a valid number between 1 and 50")
            user_input = int(input("Select the password range (1-50): "))
        
        # 使用user_input作为密码长度,拼接成字符串
        password_chars = random.sample(characters, user_input)
        password = ''.join(password_chars)
        
        print(password)

# 调用函数运行
Randomize()

额外说明

  • random.sample()会从字符列表中随机选择指定数量的不重复字符,适合生成无重复字符的密码;如果允许重复字符,可以改用random.choices()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:05:23