I'm working on a project for school and can't figure out how to get the average of the positive user entered inputs and the average of the negative user entered inputs and have it display. I think I'm on the right track and I feel that I'm only missing a step or two to get the program completed. This is what I have to start:
print("(enter '0' to stop)")
cout_pos=0
count_neg=0
sum= 0.0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum = sum + num
count_pos +=1
if num < 0:
sum = sum + num
count_neg -=1
if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum/(count_pos-1))
print('negative average: ' ,sum/(count_neg))
Thanks for the help!
To have this working correctly you need to create separete variables for the sumation, like you are doing with the counts, otherwise you'll have overlapping:
print("(enter '0' to stop)")
count_pos=0
count_neg=0
sum_pos= 0
sum_neg= 0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum_pos = sum_pos + num
count_pos +=1
if num < 0:
sum_neg = sum_neg + num
count_neg -=1
if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum_pos/(count_pos))
print('negative average: ' ,sum_neg/(count_neg))
Output:
enter value: 4
enter value: 4
enter value: 3
enter value: 3
enter value: -2
enter value: -4
enter value: 0
positive average: 3.5
negative average: 3.0
This is another version:
def average(lst):
""" Count average from the list of numbers """
return sum(lst) / len(lst)
positive = [] # list of positive numbers
negative = [] # list of negative numbers
num = None
print("(enter '0' to stop)")
while True:
try: # try to enter float values
num = float(input('enter value: '))
except ValueError: # non-number was entered
print('please, enter only numbers')
continue # start from beginning of while loop
if num > 0: # if positive, append number to positive list
positive.append(num)
elif num < 0: # if negative, append number to negative list
negative.append(num)
else: # if zero, exit from the while loop
break
# Use f-strings to print for Python 3.7 and higher
if len(positive):
print(f'positive average: {average(positive)}')
if len(negative):
print(f'negative average: {average(negative)}')
if len(positive) == 0 and len(negative) == 0:
print('no values were entered')
The output is:
(enter '0' to stop)
enter value: 1.5
enter value: 3.7
enter value: a
please, enter only numbers
enter value: 4.6
enter value: -2.78
enter value: -9.99
enter value: 0a
please, enter only numbers
enter value: 0.0
positive average: 3.266666666666667
negative average: -6.385
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.