如何在python中使用max命令或类似的“inside”while命令?

时间:2017-07-16 14:48:55

标签: python python-2.7 python-3.x max

def main():

    line = input("How many numbers are included? \n")

    numbers_included = int(line)

    i = 0

    sum = 0
    print("Each number should be placed on separate row")
    while i < numbers_included:
        line = input ("")
        number = int(line)
        sum = sum + number
        i = i + 1
    average = sum / numbers_included
    print("Average is",average)
    print("and the biggest digit is", max(number))

main()

如何在上面的代码中打印最大数字?

提前致谢!

3 个答案:

答案 0 :(得分:0)

如果您想使用max,则需要收集一个可迭代的数字以传递到max()

...
numbers = [] # here
...
while i < numbers_included:
    line = input ("")
    number = int(line)
    numbers.append(number) # here
    ...
average = sum / numbers_included
print("Average is", average)
print("and the biggest digit is", max(numbers))

答案 1 :(得分:0)

我认为在这种情况下,使用for循环最好不使用while循环。并将数字附加到列表中,并使用sum()max()列表操作来完成您的工作。

def main():

    line = input("How many numbers are included? \n")

    numbers_included = int(line)
    val_sum = 0
    numbers = []
    print("Each number should be placed on separate row")

    for _ in range(numbers_included):
        line = int(input ())
        numbers.append(line)

    val_sum = sum(numbers)
    average = val_sum / numbers_included
    print("Average is",average)
    print("and the biggest digit is", max(numbers))

main()

答案 2 :(得分:0)

或者,为了有趣和简洁

    if __name__ == "__main__":
        n_lines_str = input("How many numbers are included? \n")
        n_lines = int(n_lines_str )
        print("Each number should be placed on separate row")

        numbers = [int(input()) for i in range(n_lines)]
        mean = sum(numbers) / len(numbers)

        print("Average is {}".format(mean))
        print("Maximum is {}".format(max(numbers)))