简体   繁体   中英

How to sum numbers entered by the user using Python and display the total?

My task is:

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work? However, my list does not append integers, only strings. Besides, the word 'done' was also appended to the list.

my code is:

x=[ ]
while True:
    line = input('enter a number: ')
    x.append(line)
    if line == 'done':
        break

my desired output is:

Enter a number: 4

Enter a number: 5

Enter a number: bad data

Enter a number: 7

Enter a number: done

16 3 5.333333333333333

My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work?

Yes, that sounds like the perfect solution.

However, my list does not append integers, only strings.

Convert the input to an int before appending it:

x.append(int(line))

This will fail if line cannot be converted to an int , so you probably actually want:

try:
    x.append(int(line))
except ValueError:
    pass

Besides, the word 'done' was also appended to the list.

Check for the string 'done' before you append it.

if line == 'done':
    break
try:
    x.append(int(line))
except ValueError:
    pass

Finally, you can use sum and len to do your calculations.

Here is what you can do, assuming the user can only input integers:

x=[]
while True:
    try:
        line = input('enter a number: ')
        if line == 'done':
            break
        x.append(int(line))
    except:
        pass
print(sum(x),len(x),sum(x)/len(x))

If the user should be able to input floats:

x=[]
while True:
    try:
        line = input('enter a number: ')
        if line == 'done':
            break
        x.append(float(line))
    except:
        pass
print(sum(x),len(x),sum(x)/len(x))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM