Write a program that keeps reading positive numbers from the user until the user entered negative numbers

Question:

Write a program that keeps reading positive numbers from the user. The program should only quit when the user enters a negative value. Once the user enters a negative value the program should print the average of all the numbers entered.

Here is my code so far

def main():
    number = 1
    numbers = []
    while (number > 0):
        number = int(input("Enter a number, put in a negative number to end: "))
        if number > 0 :
            numbers.append(number)
    ratarata = len(numbers)
    print ("Average number entered: ", ratarata)
main()

This is the output:

screenshot of output

Asked By: nopedawn

||

Answers:

sum_num=0
count=0
while True:
    val=int(input())
    if val>=0:
       sum_num+=val
       count+=1
    else:
      break 
try:
   print(sum_num/count)
except ZeroDivisionError:
    print(0)  

ZeroDivisionError will come when your first input in not positive number
while True: is infinite loop which will take infinite input until condition are true.

Answered By: zeeshan12396

Rather than having an item counter and a running total, use a list as follows:

list_ = list()
while (n := int(input("Enter a number, put in a negative number to end: "))) >= 0:
    list_.append(n)
print('Average number entered: ', sum(list_) / len(list_) if list_ else 0)

Note:

This will fail if the input cannot be converted to int

Answered By: DarkKnight

This is my working answer

number=1
numbers=[]
while number>0:
    number=float(input("Enter a positive number. (or a negative number to quit)"))
    if number>0:
        numbers.append(number)
print("The sum of your numbers is", sum(numbers))
print("The average is", (sum(numbers)/len(numbers)))
Answered By: Colbzyk
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.