Python3 - TypeError:“float”和“NoneType”的实例之间不支持“>”

Gab*_*Lee 3 traceback python-3.x

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

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

这是我的代码行:

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))
Run Code Online (Sandbox Code Playgroud)

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

谢谢

pax*_*blo 9

关于:

if smallest is None:
    smallest = num
Run Code Online (Sandbox Code Playgroud)

您正确设置smallest为第一个值,但您没有largest.

这意味着,对于第一个值,表达式num > largest将等效于FloatVariable > NoneVariable,这是您看到的错误的原因。

更好的方法是这样的:

if smallest is None:
    smallest = num
    largest = num
elif num > largest:
    largest = num
elif num < smallest:
    smallest = num
Run Code Online (Sandbox Code Playgroud)

这具有使用知识的优点smallestlargest 将或者两者None在开始时,或二者的非None第一值之后(第一值将固有既当前最小最大值)。

它也不会做第二个if前值为块-现在是没有必要的,你设置smallest largest该值。


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

if smallest is None:
    smallest = num
Run Code Online (Sandbox Code Playgroud)