![]() |
having issues with the int() function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: having issues with the int() function (/thread-29864.html) |
having issues with the int() function - megu - Sep-23-2020 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)) 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
RE: having issues with the int() function - ndc85430 - Sep-23-2020 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.
RE: having issues with the int() function - perfringo - Sep-23-2020 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': |