Bogdan Rasputin
Bogdan Rasputin

Reputation: 53

How to find averages?

I'm trying to make a program to find the Mean average with a set of numbers. It works at the moment but I was wondering if there is any way to make it easier or cleaner. It is pretty messy and bad. Is there anyway I can use loops or anything to make it easier?

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

It keeps going after this, all the way up to 15. I just made it manually.

Upvotes: 0

Views: 406

Answers (5)

AHBLUBLU
AHBLUBLU

Reputation: 33

I have one method to do it which is a nested loop

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}')

Upvotes: 0

Charles Landau
Charles Landau

Reputation: 4265

You can just write it so that the user can just indefinitely input numbers:

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)))

Upvotes: 1

yasserkabbout
yasserkabbout

Reputation: 201

Try to store the user's input in an array then perform the following:

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 )

Upvotes: 0

Kingsley
Kingsley

Reputation: 14906

A common way of handling this is with a for() loop

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))

Upvotes: 1

NgoCuong
NgoCuong

Reputation: 2319

Try a function. Function will group the codes and can be used to call multiple of times.

An example

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)

Upvotes: 0

Related Questions