Python Forum
having issues with the int() function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
having issues with the int() function
#1
Hi I'm currently working through an exercise and having trouble with it

The problem 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 code:
a = []
while True:
    x = input('Enter a number: ')
    if x == 'done':
        break
    else:
        try:
            int(x)
            a.append(x)
        except ValueError:
            print('Not a number')
print(len(a), sum(a), sum(a)/len(a))
Error:
Traceback (most recent call last): File "C:\Users\elong\OneDrive\Desktop\Python\playground.py", line 13, in <module> print(len(a), sum(a), sum(a)/len(a)) TypeError: unsupported operand type(s) for +: 'int' and 'str'
I believe the issue is the int() function isn't converting the input before it adds it to the list, any help is greatly appreciated
Reply


Messages In This Thread
having issues with the int() function - by megu - Sep-23-2020, 02:52 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Issues with Lambda Function fad3r 5 3,859 May-22-2018, 04:13 PM
Last Post: fad3r

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020