我如何打印较小的值?

时间:2015-03-01 20:58:55

标签: python

我是python的新手,我在下面写了几行代码,但是无法从输入中打印最小的数字。

largest = 0
smallest = 0

while True:
    num = raw_input("Enter a number:")
    if num == "done" : break
    try:
        num = int(num)
    except:
        print "invalid"
        continue
    if num is smallest:
          smallest = num
    if num > largest:
          largest = num

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

下面是我的输出,它确实打印了正确的最大值(无论我输入什么),但最小值始终为零。

Enter a number:34
Enter a number:12000
Enter a number:dds
invalid
Enter a number:done
Minimum 0 Maximum 12000=====> see minimum is "0" should be 34?

1 个答案:

答案 0 :(得分:2)

这是预期的行为。实际上,你的第二个陈述是:

smallest = 0

0小于34,因此smallest不会更新。

一种可能的解决方案是从第一个元素中初始化smallestlargest

largest = None
smallest = None

while True:
    num = raw_input("Enter a number:")
    if num == "done" : break
    try:
        num = int(num)
    except:
        print "invalid"
        continue

    if smallest is None: # or largest is None, it's the same
        smallest = num
        largest = num

    if num < smallest:
          smallest = num
    if num > largest:
          largest = num

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

此外,你有关于运营商is的错字或误解。这样:

if num is smallest:
    smallest = num

应该是:

if num < smallest:
    smallest = num