gpt4 book ai didi

python-3.x - Python3 - 类型错误 : '>' not supported between instances of 'float' and 'NoneType'

转载 作者:行者123 更新时间:2023-12-03 16:45:57 26 4
gpt4 key购买 nike

我最近参加了一门 Python 类(class),我正在做的练习希望我找到最大和最小的数字。如果我输入一个“字符串”,那么它会提示“无效输入”。这是我到目前为止所得到的,但我收到了回溯错误:

Traceback (most recent call last):
File "FindingSmallestLargestNum.py", line 15, in <module>
if num > largest:
TypeError: '>' not supported between instances of 'float' and
'NoneType'

这是我的代码行:
largest = None
smallest = None

while True:
num = input("Enter a number: ")
if num == "done": break
try:
num = float(num)
except:
print("Invalid input")
continue

if smallest is None:
smallest = num
if num > largest:
largest = num
elif num < smallest:
smallest = num

print("Maximum is",int(largest))
print("Minimum is",int(smallest))

我不确定为什么会收到此错误代码。请帮忙。

谢谢

最佳答案

关于:

if smallest is None:
smallest = num
您设置正确 smallest到第一个值,但您不对 largest 执行相同操作.
这意味着,对于第一个值,表达式 num > largest将等同于 FloatVariable > NoneVariable ,这就是您看到的错误的原因。
更好的方法是:
if smallest is None:
smallest = num
largest = num
elif num > largest:
largest = num
elif num < smallest:
smallest = num
这具有使用知识的优势 smallestlargest要么都是 None在开始时,或两者都不是 None在第一个值之后(第一个值本质上是当前的最小值和最大值)。
它也没有做第二个 if阻止第一个值 - 现在您不需要设置 smallestlargest对于那个值。

在我回答这个问题大约三年后重新发现了这个问题,并且在有了更多的 Python 经验之后,在我看来我们可以让它更简洁(这通常会导致更好的可维护性:
smallest, largest = None, None

while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = float(num)
except:
print("Invalid input")
continue

if smallest is None:
smallest, largest = num, num
if num > largest:
largest = num
elif num < smallest:
smallest = num

print(f"Maximum is {largest}")
print(f"Minimum is {smallest}")

关于python-3.x - Python3 - 类型错误 : '>' not supported between instances of 'float' and 'NoneType' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50809022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com