在Python 2中:
raw_input()
在Python 3中,我得到一个错误:
name 'raw_input'没有定义
在Python 2中:
raw_input()
在Python 3中,我得到一个错误:
name 'raw_input'没有定义
当前回答
这在python3中有效。X和2.x:
# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))
其他回答
从Python 3开始,raw_input()被重命名为input()。
Python 3.0更新:内置程序节第二项。
这在python3中有效。X和2.x:
# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))
下面这个怎么样?应该允许您使用raw_input或Python2和Python3中的input,具有Python2的raw_input的语义(也就是Python3的输入的语义)
# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x
try: input = raw_input
except NameError: raw_input = input
正如其他人所指出的,raw_input函数在Python 3.0中已被重命名为input,您真的应该读一本最新的书籍,但我想指出的是,还有更好的方法来查看脚本的输出。
From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.
使用命令提示符
当您查看包含Python程序的文件夹窗口时,按住shift并右键单击窗口白色背景区域的任何位置。弹出的菜单应该包含一个条目“在这里打开命令窗口”。(我认为这适用于Windows Vista和Windows 7。)这将打开一个命令提示窗口,看起来像这样:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Weeble\My Python Program>_
要运行您的程序,输入以下内容(替换您的脚本名称):
python myscript.py
...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.
使用闲置
IDLE是一个简单的程序编辑器,随Python一起安装。在其他功能中,它可以在窗口中运行程序。右键单击你的.py文件,选择“在IDLE中编辑”。当程序出现在编辑器中时,按F5或从“运行”菜单中选择“运行模块”。程序将在程序结束后保持打开的窗口中运行,您可以在其中输入Python命令立即运行。
Timmerman的解决方案在运行代码时工作得很好,但如果你不想在使用pyflakes或类似的linter时得到未定义的名称错误,你可以使用以下方法:
try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass