简体   繁体   中英

Python gives error if I run this code from cmd, however runs fine if I run it from Jupyter

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

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 (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM