-1

I tried writing a program that reads numbers using a loop, evaluates the total numbers, prints it and stops when you type done using try and except.

initiator = True
myList = []

while initiator:
    try:
        userIn = int(input('Enter any number >>  '))
        myList.append(userIn)
        print(myList)

    except ValueError:
        if str(userIn):
            if userIn == 'done':
                pass
            average = eval(myList)
            print(average)
            initiator = False

        else:
            print('Wrong input!\nPlease try again')
            continue
John Gordon
  • 29,573
  • 7
  • 33
  • 58
Kimm Muna
  • 3
  • 3
  • 2
    And so what is your actual question? If this code isn't working as you want, you need to explain. Are you getting errors, or unexpected output? – John Gordon Dec 13 '22 at 00:55
  • Stopping by to say - [don't use eval](https://stackoverflow.com/a/1832957/4935162). Not sure why it's in this code in the first place. Edit: okay, it doesn't do what you think it does. See Barmar's answer – Yarin_007 Dec 13 '22 at 00:59
  • It says: average = eval(myList) TypeError: eval() arg 1 must be a string, bytes or code object – Kimm Muna Dec 13 '22 at 01:00
  • 1
    What did you think calling `eval()` on a list would do? – John Gordon Dec 13 '22 at 01:13

1 Answers1

0

When int() raises an exception, it doesn't set userIn, so you can't compare userIn with done.

You should separate reading the input and callint int().

while True:
    try:
        userIn = input('Enter any number >>  ')
        num = int(userIn)
        myList.append(num)
        print(myList)

    except ValueError:
        if userIn == 'done':
            break
        else:
            print('Wrong input!\nPlease try again')

average = sum(myList) / len(myList)
print(average)

eval() is not the correct way to get the average of a list. Use sum() to add up the list elements, and divide by the length to get the average.

Barmar
  • 741,623
  • 53
  • 500
  • 612