0

My code:

Basically, I am reading in inputs in a list. It should give an error if its not an integer, and skip that input and stop when i write "done". Then I am creating a count, sum and average, which I print.

total = 0
count = 0
list = []

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        fnum = float(num)
        list.append(fnum)
    except:
        print("Invalid input")
        print(fnum, type(fnum))
        continue
print(list)
for i in list:
    count += 1
    total += i
print(total, count, "Average: ", total/count)

Error message

Like I said, it runs fine from Jupyter or Colab, but I get the following error message from cmd:

If I enter a random string:

Traceback (most recent call last):
  File "C:location\file.py", line 6, in <module>
    num = input("Enter a number: ")
  File "<string>", line 1, in <module>
NameError: name 'asd' is not defined

If I enter done:

Traceback (most recent call last):
  File "C:location\file.py", line 6, in <module>
    num = input("Enter a number: ")
  File "<string>", line 1, in <module>
NameError: name 'done' is not defined
  • Are you running this in python 2? – MisterMiyagi Mar 12 '20 at 15:34
  • Using a bare `except` like that is bad practice, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. Naming a variable `list` is also a terrible idea, be careful! – AMC Mar 12 '20 at 19:01
  • thank you! yes, unfortunately i was running this in python 2. but when i typed python3 in cmd, it worked – szutsmester Mar 12 '20 at 20:59

1 Answers1

1

Probably you're running it using Python 2. Jupyter uses Python 3, so no problem. However in python2 the input() function takes an input and executes it as code. You entered asd - and python complains there is no asd variable (same for done). Run it using python 3, or use the raw_input() function which has the same effect like input() in python 3 - but in python 2 (i.e. no running code).

Edit:

Assuming you're using python filename.py to run your code - try python -V. I'll give you the python version. If I correct, most of the time you can access python3 using python3 instead of just python.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77