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
#2
int returns the converted value, so it doesn't modify x. You're just throwing away the returned value on line 8, instead of appending it to your list.
Reply
#3
If using 3.8 <= Python then it is possible to take advantage of assignment expression (walrus operator) and instead of while True write:

while (answer := input('Enter a number: ')) != 'done':
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issues with Lambda Function fad3r 5 3,681 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