0

sorry for the stupid question, but I can't get out of this thing in any way, I'm a beginner. I need to write a code that asks the user to write a series of int one at the time using a while function. When the user has inserted all the numbers, to stop the series he'll write a specific string. When it's done, I need the code to print the sum and the average of all the numbers inserted. The user can't insert them all in one time, he needs to enter one at the time.

I tried something like this: but there's no way it'll work. Implementing items in a list and then operate on the list is possible, but I had no idea on how to do that more easily than summing every element each time.

(my initial code:)

count = 0
total = 0
while():
    new_number = input('> ')
    if new_number == 'Done' :
        break
    count = count + 1
    total = total + number
print(total)
print(total / count)

Don't mind about data being a string or an int, as long as it's just an error that IDLE would tell me. I just would like to know what's logically wrong in my code. Thank you in advance.

CDJB
  • 14,043
  • 5
  • 29
  • 55

2 Answers2

1

You were really close, I made a couple of changes - firstly I changed while(): to while True:, so that the loop runs until break is hit. Secondly I altered total = total + number to total = total + int(new_number) - corrected variable name and convert string returned by input() to an int. Your logic is fine.

Corrected Code:

count = 0
total = 0
while True:
    new_number = input('> ')
    if new_number == 'Done' :
        break
    count = count + 1
    total = total + int(new_number)
print(total)
print(total / count)
CDJB
  • 14,043
  • 5
  • 29
  • 55
0

Using a list is actually not that hard. Here's how:

Firstly make the corrections from CDJB's answer.

Create an empty list. Add each new_number to the list. Use sum() and len() to get the total and count.

nums = []
while True:
    new_number = input('> ')
    if new_number == 'Done':
        break
    nums.append(int(new_number))
total = sum(nums)
count = len(nums)
print(total)
print(total / count
wjandrea
  • 28,235
  • 9
  • 60
  • 81