我最近正在学习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'


这是我的代码行:

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-3.x - Python3-TypeError:“float”和“NoneType”的实例之间不支持“>”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50809022/

10-11 16:02