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

求助:TypeError: 'int'与'str'实例间不支持'<='运算

TypeError: '<=' not supported between instances of 'int' and 'str' 解决方法

错误原因

报错行password="".join(random.sample(characters,USER_INP))出现类型不匹配错误,因为simpledialog.askstring()获取的用户输入是字符串类型,而random.sample()的第二个参数要求传入整数,内部执行比较操作时,字符串和整数无法直接用<=比较,导致报错。

你之前尝试的password="".join(int(random.sample(characters,USER_INP)))是错误的,因为random.sample()返回的是字符列表,不能直接转换为整数,应该先将用户输入的字符串转为整数。

修复方案

  1. 将用户输入的USER_INP转换为整数,同时添加异常处理,避免用户输入非数字内容时崩溃
  2. 优化characters字符串,无需重复多次,一次定义即可(重复多次不会增加字符种类,只是重复已有字符,不影响功能但冗余)

修改后的完整代码

import random
import tkinter
from tkinter import simpledialog

# 定义密码字符集,无需重复多次
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890"

ROOT = tkinter.Tk()
ROOT.withdraw()

# 获取用户输入并转换为整数,添加异常处理
try:
    USER_INP = simpledialog.askstring(title="Secure Password Gen",
                                      prompt="How many characters do you want your password to be? *password will be in Terminal*")
    # 转换为整数
    password_length = int(USER_INP)
    # 生成密码:random.sample返回字符列表,用join拼接成字符串
    password = "".join(random.sample(characters, password_length))
    print("The Password is: ", password)
except (ValueError, TypeError):
    print("请输入有效的数字!")

额外说明

  • 如果需要允许密码中出现重复字符(比如密码长度大于字符集种类),可以将random.sample()替换为random.choices(),示例:
    password = "".join(random.choices(characters, k=password_length))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:10:26