为什么 Python 3 中的`input` 抛出 NameError: name... is not defined [英] Why is `input` in Python 3 throwing NameError: name... is not defined

查看:25
本文介绍了为什么 Python 3 中的`input` 抛出 NameError: name... is not defined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量 test,在 Python 2.x 中可以正常工作.

I have a string variable test, in Python 2.x this works fine.

test = raw_input("enter the test") 
print test

但在 Python 3.x 中,我这样做:

But in Python 3.x, I do:

test = input("enter the test") 
print test

使用输入字符串sdas,我收到一条错误消息

with the input string sdas, and I get an error message

Traceback (most recent call last):
 File "/home/ananiev/PycharmProjects/PigLatin/main.py", line 5, in <module>
    test = input("enter the test")
 File "<string>", line 1, in <module> 
NameError: name 'sdas' is not defined

推荐答案

您正在使用 Python 2 解释器运行 Python 3 代码.如果不是,您的 print 语句会抛出一个 SyntaxError 在它提示您输入之前.

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

结果是您使用的是 Python 2 的 input 尝试对您的输入(大概是 sdas)进行eval,发现它是无效的 Python,然后死亡.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

这篇关于为什么 Python 3 中的`input` 抛出 NameError: name... is not defined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆