2017-07-16 76 views
2
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() 

如何將最大數字打印到上面的代碼中?如何在python中使用max命令或類似的「inside」命令?

在此先感謝!

回答

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)) 
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() 
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))) 
+0

有沒有需要調用'len';你已經知道有多少數字('n_lines')。 – chepner

+0

當然,你知道他們應該是平等的。儘管如此,len呼叫是不變的,這意味着平均值實際上是列表中的內容的平均值。否則,我們知道這是一個意味着提供了len == n _...但這是一個間接邏輯層次。 –

相關問題