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

Python中添加lvl >= list后出现unorderable types错误的原因咨询

问题分析:为何添加and lvl >= list条件会触发TypeError?

先还原你的代码和遇到的错误场景:

你的代码

lvl=int(input("Level(1-15) => "))
val=1
list(range(1, 16))
if lvl != list and lvl >= list:
    print("Invalid Input. Please enter an integer value between 1 to 15")

输入7时的错误输出

Level(1-15) => 7
Traceback (most recent call last):
  File "./test.py", line 11, in <module>
    if lvl != list and lvl >= list:
TypeError: unorderable types: int() >= type()

错误根源:混淆了list内置类型和自定义列表变量

这里的核心问题很直白:你写的list是Python内置的类型(类),而不是你以为的“1到15的数字列表”。

你虽然写了list(range(1, 16))这行代码,但没有把生成的列表赋值给任何变量——这行代码执行后就直接被丢弃了,完全没被后续的条件判断用到。

当你写lvl >= list时,本质是在尝试把一个整数(比如输入的7)和list这个类型(类似int、str这类内置类型)做大小比较,Python完全无法理解“整数”和“类型”怎么比大小,所以直接抛出了TypeError。

而移除这个条件后,剩下的lvl != list其实逻辑上也是错的,但Python允许判断“整数是否不等于一个类型”(结果永远是True,因为7和list类型完全不是一回事),所以不会触发类型错误,但你的条件判断根本没达到“检查输入是否在1-15之间”的目的。


修正后的正确写法

如果你想检查输入的lvl是否在1到15之间,根本不需要创建列表,直接用数值范围判断更简洁高效:

lvl = int(input("Level(1-15) => "))
if not (1 <= lvl <= 15):
    print("Invalid Input. Please enter an integer value between 1 to 15")

如果一定要用列表来判断(比如后续有其他业务需求),记得把生成的列表赋值给变量再使用:

lvl = int(input("Level(1-15) => "))
valid_levels = list(range(1, 16))  # 把1-15的列表存到变量里
if lvl not in valid_levels:
    print("Invalid Input. Please enter an integer value between 1 to 15")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:19:53