Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果我从cmd运行此代码,Python会给出错误,但是如果我从Jupyter运行,则运行良好 我的代码:_Python_Input_While Loop_Try Except - Fatal编程技术网

如果我从cmd运行此代码,Python会给出错误,但是如果我从Jupyter运行,则运行良好 我的代码:

如果我从cmd运行此代码,Python会给出错误,但是如果我从Jupyter运行,则运行良好 我的代码:,python,input,while-loop,try-except,Python,Input,While Loop,Try Except,基本上,我是在读列表中的输入。如果不是整数,它应该给出一个错误,并跳过该输入,在我写“完成”时停止。然后我创建一个计数、总和和平均值,并打印出来 total = 0 count = 0 list = [] while True: num = input("Enter a number: ") if num == "done": break try: fnum = float(num) list.append(fnum)

基本上,我是在读列表中的输入。如果不是整数,它应该给出一个错误,并跳过该输入,在我写“完成”时停止。然后我创建一个计数、总和和平均值,并打印出来

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)
错误消息 正如我所说,它在Jupyter或Colab中运行良好,但我从cmd中得到以下错误消息:

如果我输入一个随机字符串:
回溯(最近一次呼叫最后一次):
文件“C:location\File.py”,第6行,在
num=输入(“输入一个数字:”)
文件“”,第1行,在
NameError:未定义名称“asd”
如果我输入done:
回溯(最近一次呼叫最后一次):
文件“C:location\File.py”,第6行,在
num=输入(“输入一个数字:”)
文件“”,第1行,在
NameError:未定义名称“完成”

您可能正在使用Python 2运行它。Jupyter使用Python3,所以没问题。但是在python2中,
input()
函数接受一个输入,并将其作为代码执行。您输入了
asd
——python抱怨没有
asd
变量(与
done
相同)。使用Python3运行它,或者使用
raw\u input()
函数,其效果与Python3中的
input()
相同,但在Python2中(即没有运行的代码)

编辑:
假设您使用的是
python filename.py
来运行代码,请尝试
python-V
。我将为您提供python版本。如果我没有记错的话,大多数情况下,您可以使用
python3
而不仅仅是
python

来访问python3。您是否在python2中运行此功能?除了像这样使用
之外,使用裸
是不好的做法,请参阅。命名变量
列表
也是一个糟糕的主意,小心!非常感谢。是的,不幸的是我在Python2中运行了这个。但是当我在cmd中输入python3时,它工作了哇,谢谢,这完全正确!我确实使用了python而不是python3,这就解决了这个问题。
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
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