在 Python 3.4 中使用 input() 时出现 NameError
NameError when using input() with Python 3.4
我是新 Python 用户,我一直在学习许多教程。这包括 运行 命令提示符中的一些代码。当我第一次测试代码时这工作正常但由于某种原因它似乎已经停止工作并且我现在在使用 Input() 时遇到错误。我已经包含了下面的代码和我收到的错误消息。
代码:
import sys
print (sys.version)
print("hello world")
myName = input("What is your name?")
print(myName)
if (myName == "Matt"):
print("Matt is great!")
elif (myName == "Bob"):
print("Bob is ok")
else:
print("Hello world")
input("Press enter to continue")
错误信息:
C:\Users\matt.xxxx>cd C:\Python34\Scripts\Projects
C:\Python34\Scripts\Projects>helloworld.py
2.7.7 (default, Jun 1 2014, 14:21:57) [MSC v.1500 64 bit (AMD64)]
hello world
What is your name?Matt
Traceback (most recent call last):
File "C:\Python34\Scripts\Projects\helloworld.py", line 6, in <module>
myName = input("What is your name?")
File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined
C:\Python34\Scripts\Projects>
我知道使用旧版本的 python 时可能会发生这种情况,但我已经检查过并且我相当确定我使用的是 3.4 版(使用 import sys 等检查过)。我最近安装了 PyCharm,这是我能想到的唯一改变的东西。该代码在 PyCharm 和 IDLE 中有效,但在命令提示符中无效。任何帮助将不胜感激。
根据您的示例,我相信您正在 运行 脚本使用 - helloworld.py
- 这将导致 Windows 查找与扩展关联的默认应用程序 .py
和 运行 它。
我猜你安装 PyCharm 时的情况,它以某种方式使 Python 2.7.7 成为 .py
文件的默认应用程序(或者从一开始就是这样) 所以当你直接 运行 .py
文件时(甚至从命令提示符)他们 运行 使用 Python 2.7.7 .
您在评论中说过,当直接从命令提示符 运行ning python
时,您将获得 python 3.4 ,因此解决问题的最简单方法是使用运行 你的脚本。
运行 它使用命令 -
python helloworld.py
作为长期解决方案,您可能需要考虑更改与 .py
文件关联的默认应用程序。您可以查看 this link 以获取有关如何操作的指南
我是新 Python 用户,我一直在学习许多教程。这包括 运行 命令提示符中的一些代码。当我第一次测试代码时这工作正常但由于某种原因它似乎已经停止工作并且我现在在使用 Input() 时遇到错误。我已经包含了下面的代码和我收到的错误消息。
代码:
import sys
print (sys.version)
print("hello world")
myName = input("What is your name?")
print(myName)
if (myName == "Matt"):
print("Matt is great!")
elif (myName == "Bob"):
print("Bob is ok")
else:
print("Hello world")
input("Press enter to continue")
错误信息:
C:\Users\matt.xxxx>cd C:\Python34\Scripts\Projects
C:\Python34\Scripts\Projects>helloworld.py
2.7.7 (default, Jun 1 2014, 14:21:57) [MSC v.1500 64 bit (AMD64)]
hello world
What is your name?Matt
Traceback (most recent call last):
File "C:\Python34\Scripts\Projects\helloworld.py", line 6, in <module>
myName = input("What is your name?")
File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined
C:\Python34\Scripts\Projects>
我知道使用旧版本的 python 时可能会发生这种情况,但我已经检查过并且我相当确定我使用的是 3.4 版(使用 import sys 等检查过)。我最近安装了 PyCharm,这是我能想到的唯一改变的东西。该代码在 PyCharm 和 IDLE 中有效,但在命令提示符中无效。任何帮助将不胜感激。
根据您的示例,我相信您正在 运行 脚本使用 - helloworld.py
- 这将导致 Windows 查找与扩展关联的默认应用程序 .py
和 运行 它。
我猜你安装 PyCharm 时的情况,它以某种方式使 Python 2.7.7 成为 .py
文件的默认应用程序(或者从一开始就是这样) 所以当你直接 运行 .py
文件时(甚至从命令提示符)他们 运行 使用 Python 2.7.7 .
您在评论中说过,当直接从命令提示符 运行ning python
时,您将获得 python 3.4 ,因此解决问题的最简单方法是使用运行 你的脚本。
运行 它使用命令 -
python helloworld.py
作为长期解决方案,您可能需要考虑更改与 .py
文件关联的默认应用程序。您可以查看 this link 以获取有关如何操作的指南