如何找到平均值?

时间:2018-11-01 00:49:30

标签: python average

我正在尝试制作一个程序,以找到具有一组数字的平均数。目前它可以工作,但我想知道是否有任何方法可以使它更容易或更清洁。这是非常混乱和糟糕的。无论如何,我可以使用循环或其他任何方式使其变得更容易吗?

NON = raw_input("How many numbers are there? ")
NON = int(NON)

if NON == 2:
    n1 = raw_input("First Number: ")
    n1 = int(n1)
    n2 = raw_input("Second Number: ")
    n2 = int(n2)
    mean = (n1 + n2)/2
    print mean
    print mean

一直持续到15。我只是手动完成。

5 个答案:

答案 0 :(得分:1)

您可以编写它,以便用户可以无限期地输入数字:

numbers = []
while True:
    numbers.append(int(raw_input("What is the next number?")))
    done = raw_input("Are you done? (Y/N) ")
    if done.lower() == "y":
        break
print("The average is {}".format(sum(numbers)/len(numbers)))

答案 1 :(得分:1)

一种常见的处理方法是使用for()循环

NON = raw_input("How many numbers are there? ")
NON = int(NON)
sum = 0
for i in range(NON):
    number = raw_input("Enter Number #"+str(i)+": ")
    number = int(number)
    sum += number
average = sum / NON
print("Average is: "+str(average))

答案 2 :(得分:0)

尝试功能。函数将对代码进行分组,并且可以多次调用。

一个例子

def average(number1, number2):
    return (int(number1) + int(number2)) / 2


NON = raw_input("How many numbers are there? ")
NON = int(NON)

    if NON == 2:
        n1 = raw_input("First Number: ")
        n2 = raw_input("Second Number: ")
        print average(n1,n2)

答案 3 :(得分:0)

尝试将用户输入存储在数组中,然后执行以下操作:

sum = 0
list = [11,22,33,44,55,66,77]
for num in list:
    sum = sum +num
average  = sum / len(list)
print ("Average of list element is ", average )

答案 4 :(得分:0)

我有一种方法可以做到这一点,那就是嵌套循环

students = int(input("How many students do you have? "))
tests = int(input("How many test for your module? "))
for x in range(students):
    x += 1
    total = 0
    print(f'****** Student # {x} ******')
    
    for y in range(tests):
        y += 1
        score = float(input(f'Test number {y}: '))
        total = (total + c)
    ave = total/tests
    print(f'The ave for student # {x} is: {ave:.1f}')