python3出现错误:NameError: name 'abchello' is not defined

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3出现错误:NameError: name 'abchello' is not defined相关的知识,希望对你有一定的参考价值。

def read_and_find_hello(py_file):
f=open(py_file)
flag=False
while True:
line=f.readline()
if line==''
break
elif "hello" in line:
flag = True
break
f.close()
return flag

print(read_and_find_hello("C:/Users/Administrator/Desktop/a.txt"))

错误提示:
Traceback (most recent call last):
File "Desktop\a.txt", line 1, in <module>
abchello
NameError: name 'abchello' is not defined
在win10 cmd 命令下运行时出现这个问题,在pycharm中运行不会出现这个问题。

参考技术A 你是怎么运行的(如果是命令行就贴命令文本)追问

cmd命令行运行结果

pycharm运行结果:

追答

运行方法错了,应该是把你最上面那一段代码另存为code.py文件,然后命令行

python code.py

NameError:名称'python'未定义[关闭]

【中文标题】NameError:名称\'python\'未定义[关闭]【英文标题】:NameError: name 'python' is not defined [closed]NameError:名称'python'未定义[关闭] 【发布时间】:2013-05-27 06:20:43 【问题描述】:

我在 Windows 命令行中遇到这个错误,进行了广泛的搜索,但没有得到完美的答案。请在下面找到错误并帮助解决。

python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>>

提前致谢,

【问题讨论】:

您是如何获得此回溯的?你输入了什么?我猜您尝试执行 python 来启动解释器,然后再次输入 python,这被解释为变量名。 你没有在“python”这个词前加上&gt;&gt;&gt;,对吧? 【参考方案1】:

您似乎正在尝试通过运行命令 python 来启动 Python 解释器。

但是解释器已经启动。它将python 解释为变量的名称,并且该名称未定义。

试试这个,你应该会看到你的 Python 安装按预期工作:

print("Hello world!")

【讨论】:

这在输入时效果很好,但是当我输入“python”时,它显示错误为名称错误:python 未定义。这意味着什么?>>> print ("hello world" ) 你好世界>>>【参考方案2】:

当您运行 Windows 命令提示符并输入 python 时,它会启动 Python 解释器。

再次键入它会尝试将 python 解释为一个变量,该变量不存在,因此不起作用:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

如果您不是从命令行执行此操作,而是直接运行 Python 解释器(python.exe 或 IDLE 的 shell),则您不在 Windows 命令行中,python 被解释为变量,你还没有定义。

【讨论】:

可能他根本没有运行命令行,而是直接运行python解释器。

以上是关于python3出现错误:NameError: name 'abchello' is not defined的主要内容,如果未能解决你的问题,请参考以下文章

NameError:名称“树”未定义

python3 安装不了xlutils模块 安装提示nameError:name file in not defined错误

错误:NameError:未定义名称“子进程”[关闭]

如何解决 OpenCV 中出现的“NameError: name 'frame' is not defined”错误?

完美解决NameError: name ‘BeautifulSoup‘ is not defined

为何会出现NameError: name 'arg' is not defined错误?如何解决