迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

python 中的错误 NameError: Name Python Is Not Defined

作者:迹忆客 最近更新:2023/07/06 浏览次数:

我们将了解什么是 NameError 以及如何修复它。 我们还将学习如何修复当我们在解释器内调用 Python 而不是 Python 中的终端时出现的 NameError: name 'python' is not Defined


修复 Python 错误 NameError: name 'python' is not defined

有时我们在Python中会遇到NameError,因为我们在代码中编写了一个变量,但我们没有告诉Python该变量是什么。

现在我们编写了一个 Python 脚本来演示如何引发错误。

name="Bob"

fave_animal="dog"

print("Hi",name,"Your favorite animal is a",fave_animal)
print("Your favorite film is", film)

在此代码中,我们定义了 name 和 fave_animal 但尚未定义 film,因此当我们运行此代码时,我们会收到 name 'film' is not Defined 错误。 这意味着 Python 不知道“film”是什么。

NameError: name 'film' is not defined

我们可以通过定义电影来解决这个问题,并且可以通过运行这个脚本来做到这一点。

film="John Wick"
print("Your favorite film is", film)

输出:

Your favorite film is John Wick

您可能收到错误的另一个原因是当您无意中错误地写了变量,例如:films,因此如果我们运行它,它会引发相同的错误。

film="John Wick"
print("Your favorite film is", films)

输出:

NameError: name 'films' is not defined

出现错误的另一种方法是假设您在任何地方定义字符串时忘记在引号内添加单词。 在我们的例子中,我们在 Python 脚本中犯了一个愚蠢的错误,如果我们运行这段代码,我们会得到同样的错误。

python

输出:

NameError: name 'Your' is not defined

大多数初学者都会犯这些类型的错误,有时会发现很难找到解决方案。

初学者犯这个愚蠢错误的另一件事是,他们尝试在 Python 解释器内调用 python,当他们在解释器内执行此命令时,他们会得到我们讨论过的相同错误。

C:\Users\Dell>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] 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

当我们运行 CMD 并输入 python 时,它会启动 Python 解释器,但再次输入它会尝试将 python 解释为变量名,但该名称未定义,因此我们收到错误。

在CMD中,不需要再次调用它来启动Python。 Python解释器已经启动了,所以不需要调用python来启动。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中错误 Address Already in Use

发布时间:2023/07/09 浏览次数:173 分类:Python

我们将通过示例介绍Python中何时出现 Address already in use 错误以及如何解决。Python 中的错误Address already in use 本文将讲述运行使用端口的程序时发生的Python堆栈错误。

Python 中错误 ValueError: Math Domain Error

发布时间:2023/07/09 浏览次数:607 分类:Python

在本篇文章中,我们的目标是探索解决 Python 中的 ValueError: math domain error 错误的不同方法。当编码方面数学(基础或高级)的使用存在固有缺陷时,Python 中通常会引发 ValueError: math domain error 错

Python 错误 Name xrange Is Not Defined

发布时间:2023/07/09 浏览次数:153 分类:Python

本篇文章将介绍如何解决 Python 中 name 'xrange' is not defined 的错误。解决Python中name 'xrange' is not defined错误 让我们尝试理解为什么会发生这个特定的错误。 让我们首先尝试复制这个问题。

Python 中错误 AttributeError: __Enter__

发布时间:2023/07/09 浏览次数:2241 分类:Python

在 Python 中,AttributeError 是在未定义 __enter__ 函数的情况下通过 with 语句使用类的对象时导致的错误。

Python 错误 Error: Invalid Command Bdist_wheel

发布时间:2023/07/09 浏览次数:847 分类:Python

在 Python 中构建 wheel 时,有时 setup.py 可能会退出并出现错误 invalid command 'bdist_wheel'。 本篇文章将讨论在 Python 中解决此问题的可能解决方案。安装wheel包来修复Python中 Error:invalid command 'bdist_

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便