返回意外值

2024-04-23 17:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这个代码的在线课程,我正在采取,你不能张贴代码,并获得具体的帮助那里。我希望这里有人能帮忙。 代码-

largest = None
smallest = None
numI = 0
while True:
    num = raw_input("Prompt you")
    if num == "done":
        break
    try:
        numI = int(num)
    except:
        print "Invalid input"
        continue
    if numI >= largest or numI < smallest:
        if numI > largest:
            largest = numI
        else:
            smallest = numI 

print "Maximum is",largest
print "Minimum is",smallest

为什么返回“最小值为零”? 我尝试了两个If循环,一个If and和Elif,现在这个嵌套循环。不管怎样我似乎都达不到设定的最小值。你知道吗

非常感谢您的帮助。你知道吗

(代码已上缴并评级,因此您不能破坏该部分:))


Tags: 代码nonetrueinputrawifisnum
2条回答

在python2中,None比任何东西都少。所以你的numI < smallest条件永远不会通过。您应该显式地测试None,以便numI设置为初始过程中的第一个值,然后它可以正常更新。你知道吗

此外,您应该只使用两个独立的检查:

if largest is None or numI > largest:
    largest = numI
if smallest is None or numI < smallest:
    smallest = numI

x<;None将始终返回false,因此需要在While True:语句中添加

if largest==None:
    largest=numI
if smallest==None:
    smallest=numI

代码:

largest = None
smallest = None
numI = 0
while True:
    num = raw_input("Prompt you")
    if num == "done":
        break
    try:
        numI = int(num)
    except:
        print "Invalid input"
        continue
    if largest==None:
        largest=numI
    if smallest==None:
        smallest=numI
    if numI > largest or numI < smallest:
        if numI > largest:
            largest = numI
        else:
            smallest = numI 

print "Maximum is",largest
print "Minimum is",smallest

注意使用print('Maximum is ' + str(largest))是一种很好的做法,因为它与3.4是交叉兼容的

相关问题 更多 >