Skip to content Skip to sidebar Skip to footer

Calculating Average From Raw_input Data In A While Loop

Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements

Solution 1:

Try the following and ask any question you might have

counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
    counter += 1
    total += number
    number = int(raw_input("Enter another number: "))
if counter == 0:
    counter = 1# Prevent division by zeroprint total / counter

Solution 2:

You need to add calculating average at the end of your code.

To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.

Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:

num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
    counter += 1
    answer += anyNumber
    anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1else:
    print answer/counter #print averageprint"Good bye!"

Solution 3:

There's another issue I think:

anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
        anyNumber = int(raw_input("Enter another number: "))

The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.

Solution 4:

A different solution, using a bit more functions, but more secure.

import numpy as np

numbers = []

whileTrue:
    # try and except to avoid errors when the input is not an integer.# Replace int by float if you want to take into account float numberstry:
        user_input = int(input("Enter any number: "))

        # Condition to get out of the while loopif user_input == -1:
            break

        numbers.append(user_input)
        print (np.mean(numbers))

    except:
        print ("Enter a number.")

Solution 5:

You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:

STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0while new_number != STOP_NUMBER:
    avg *= (count-1)/count
    avg += new_number/countnew_number=int(raw_input("Enter any number: "))
    count += 1

Post a Comment for "Calculating Average From Raw_input Data In A While Loop"