繁体   English   中英

如何找到输入数字的最大值

[英]how do I find the max of inputed numbers

如何找到输入数字的最大值? 到目前为止,这就是我所拥有的。 它给我一个错误消息:'“”“对象是不可迭代的”

def greatest(num):
    for index in range(10):
        num=input('Enter the number of units sold')
    print max(num)

您可以将它们全部放入列表中,然后在列表上运行max() 或者(如果不需要其他任何列表,则可以使用以下方法简单地维护自己的最大值):

def greatest(num):   # why num here??
    maxnum = -1
    for index in range(10):
        num = input ('Enter the number of units sold')
        if num > maxnum:
            maxnum = num
    print maxnum

您需要将数字累积在列表或其他一些可迭代的数据结构中:

def greatest():
    data = [input('Enter the number of units sold') for _ in range(10)]
    print max(data)

您需要将您从用户那里得到的数字保存在数据结构中,然后在完成收集后找到最大值。 现在,您只是在每次迭代中覆盖num的值,这根本无济于事,因为您无法检查先前的输入数字。 这就是为什么您从max那里得到一个错误,并期望有一些事情要反复进行。 到目前为止,您将拥有类似的功能,

def greatest():
    l = []
    for index in range(10):
        l.append(input('Enter the number of units sold'))
    return max(l)

但这会更好:

def greatest():
    return max(input('Enter the number of units sold') for _ in xrange(10))

该错误消息是因为max为您提供了一系列数字中最大的数字,而input返回了一个int。

您可能想做的是:

def greatest(num):
    numbers = []
    for index in range(10):
        numbers.append(input('Enter the number of units sold'))
    print max(numbers)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM