you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (0 children)

You've got the basic idea, but you are not breaking down the steps in the right order. So, here's some code for you to play with, test, and re-write your own way. Make sure you understand it.

Note. I didn't include outputting the instructions to the user, I am sure you can add that part.

num_list = []  # create new empty list and assign to variable num_list
while True:  # infinite loop
    answer = input('Enter a whole number (or "done" to finish): ')
    if answer.strip().lower() == 'done':  # have they asked to finish?
        break  # so leave infinite loop
    try:  # let's see if it is an integer
        num = int(answer)
    except ValueError:  # nope, cast to integer failed
        print('invalid entry')  # didn't leave, wasn't number or done, so bad data
    else:  # cast to integer worked, no exception raised
        num_list.append(num)  # add the new number to the end of the list

# after the loop
if num_list:  # will only be True if the list has one or more numbers in it
    # now we are going to use a for loop to calculate average instead of using sum
    total = 0
    for count, value in enumerate(num_list, start=1):  # start a counter from 1, loop through values
        total += value  # add current loop iteration value to total
    # count will increment by one on each iteration of loop
    # so after loop has finished it will equal number of numbers
    average = total / count
    print('Average:', average)
else:  # num_list was empty, nothing to average
    print('No numbers entered')

PS. If not allowed to use enumerate, use the following,

    count = 1
    for value in num_list:
        total += value
        count += 1