在Python 2.7中找到最大和最小的

时间:2016-05-29 00:00:47

标签: python python-2.7

我有一个作业,我让用户选择随机数,这个程序会找到所有这些数字之间的最小和最大,如果没有输入数字,它会认为它是无效的输入。 这是我写的代码:

largest = None
smallest = None

while True:
inp = raw_input("Enter a number: ")

if inp == 'done': break
if len(inp) < 1: break

try:
    num = int(inp)
except:
    print "Invalid input"
    continue

if smallest is None:
    smallest = num
elif inp < smallest:
    smallest = num

if largest is None:
    largest = num
elif inp > largest:
    largest = num

print "Maximum is %r" % (largest)
print "Minimum is %r" % (smallest)

问题是,为什么它不起作用? 这是我尝试的一些随机数字,并且有些奇怪。 Here I executed the code in the first part and got weird answers, and I executed it again with different numbers and got it right.

2 个答案:

答案 0 :(得分:2)

您混淆了<>,并且您将inp字符串与smallestlargest进行比较而不是{{1} }}

答案 1 :(得分:1)

你的缩进是错误的,你犯了很多错误。看看这段代码。 在if-then-else中,您必须将numsmallestlargest进行比较,而不是inp

largest = None
smallest = None

while True:
    inp = raw_input("Enter a number: ")

    if inp == 'done': break
    try:
        num = int(inp)
    except:
        print "Invalid input"
        continue

    print num
    if smallest is None: smallest = num
    elif num < smallest: smallest = num

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

print "Maximum is %r" % (largest)
print "Minimum is %r" % (smallest)