Zee Dhlomo
Zee Dhlomo

Reputation: 69

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 to:

this what I have so far:

num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
        anyNumber = int(raw_input("Enter another number: "))
        counter += anyNumber
        answer = counter + anyNumber        
print answer
print "Good bye!"

Upvotes: 1

Views: 12474

Answers (8)

Shwarthog
Shwarthog

Reputation: 116

Here's my own take on what you're trying to do, although the solution provided by @nj2237 is also perfectly fine.

# Initialization
sum = 0
counter = 0
stop = False

# Process loop
while (not stop):
    inputValue = int(raw_input("Enter a number: "))

    if (inputValue == -1):
        stop = True
    else:
        sum += inputValue
        counter += 1 # counter++ doesn't work in python

# Output calculation and display
if (counter != 0):
    mean = sum / counter
    print("Mean value is " + str(mean))

print("kthxbye")

Upvotes: 0

Ramesh Pasham
Ramesh Pasham

Reputation: 91

There is another way of doing..

nums = []
while True:
    num = int(raw_input("Enter a positive number or to quit enter -1: "))
    if num == -1:
        if len(nums) > 0:
            print "Avg of {} is {}".format(nums,sum(nums)/len(nums))  
        break
    elif num < -1:
        continue
    else:
        nums.append(num)

Upvotes: 0

Chamath
Chamath

Reputation: 2044

I would suggest following.

counter = input_sum = input_value = 0

while input_value != -1:
    counter += 1
    input_sum += input_value
    input_value = int(raw_input("Enter any number: "))

try:
    print(input_sum/counter)
except ZeroDivisionError:
    print(0)

You can avoid using two raw_input and use everything inside the while loop.

Upvotes: 0

Eugene K
Eugene K

Reputation: 388

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 = 0
while new_number != STOP_NUMBER:
    avg *= (count-1)/count
    avg += new_number/count
    new_number = int(raw_input("Enter any number: "))
    count += 1

Upvotes: 0

Mathieu
Mathieu

Reputation: 5746

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

import numpy as np

numbers = []

while True:
    # 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 numbers
    try:
        user_input = int(input("Enter any number: "))

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

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

    except:
        print ("Enter a number.")

Upvotes: 0

nj2237
nj2237

Reputation: 1278

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 -1
else:
    print answer/counter #print average
print "Good bye!"

Upvotes: 1

jsmolka
jsmolka

Reputation: 800

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 zero
print total / counter

Upvotes: 2

Shwarthog
Shwarthog

Reputation: 116

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.

Upvotes: 0

Related Questions