Python: Finding Average of Numbers

Viewed 2254

My task is to: "Write a program that will keep asking the user for some numbers. If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places. If at any point a 0 is entered, that should not be included in the calculation of the average"

I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0. This is my current code:

count = 0
sum = 0
number = 1
while number >= 0:
    number = int(input())
    if number == '\n':
        print ('hey')
        break
    if number > 0:
        sum = sum + number
        count= count + 1
    elif number == 0:
        count= count + 1
    number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
3 Answers

Try this:

amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
    number = input()
    if not number: # Breaks out if nothing is entered
        break
    if int(number) != 0: # Only add to the variables if the number input is not 0
        nums+=int(number)
        amount += 1

print(round(nums/amount,2)) # Print out the average rounded to 2 digits

Input:

1
2
3
4

Output:

2.5

Or you can use numpy:

import numpy as np
n = []
while True:
    number = input()
    if not number: # Breaks out if nothing is entered
        break
    if int(number) != 0: # Only add to the variables if the number input is not 0
        n.append(int(number))

print(round(np.average(n),2)) # Print out the average rounded to 2 digits

You're very close! Almost all of it is perfect!

Here is some more pythonic code, that works. I've put comments explaining changes:

count = 0
sum = 0
# no longer need to say number = 1
while True:  # no need to check for input number >= 0 here
    number = input()
    if number = '':  # user just hit enter key, input left blank
        print('hey')
        break
    if number != 0:
        sum += int(number)  # same as sum = sum + number
        count += 1  # same as count = count + 1
    # if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}')  # same as '... {:.2f} ...'.format(count/sum)

Why your code didn't work:

When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.

I really hope this helps you learn!

A list can store information of the values, number of values and the order of the values. Try this:

numbers = []
while True:
    num = input('Enter number:')
    if num == '':
        print('Average is', round(sum(numbers)/len(numbers), 2))   # print
        numbers = []   # reset
    if num != '0' and num != '': numbers.append(int(num))  # add to list

Benefit of this code, it does not break out and runs continuously.

Related