How do I use raw_input in Python 3?

Question:

In Python 2:

raw_input()

In Python 3, I get an error:

NameError: name ‘raw_input’ is not defined

Asked By: Lonnie Price

||

Answers:

Starting with Python 3, raw_input() was renamed to input().

From What’s New In Python 3.0, Builtins section second item.

Answered By: balpha

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))
Answered By: Cees Timmerman

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.

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.

Use a command-prompt

When you’re looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:

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

C:UsersWeebleMy Python Program>_

To run your program, type the following (substituting your script name):

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.

Use IDLE

IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.

Answered By: Weeble

Timmerman’s solution works great when running the code, but if you don’t want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass
Answered By: jmagnusson

Here’s a piece of code I put in my scripts that I wan’t to run in py2/3-agnostic environment:

real_raw_input = vars(__builtins__).get('raw_input',input)

Now you can use real_raw_input. It’s quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it’s not important.

In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It’s better stay on the safe side.

Answered By: ChewbaccaKL

A reliable way to address this is

from six.moves import input

six is a module which patches over many of the 2/3 common code base pain points.

Answered By: tacaswell

Probably not the best solution, but before I came here I just made this on the fly to keep working without having a quick break from study.

def raw_input(x):
  input(x)

Then when I run raw_input('Enter your first name: ') on the script I was working on, it captures it as does input() would.

There may be a reason not to do this, that I haven’t come across yet!

Answered By: Danijel-James W

How about the following one? Should allow you to use either raw_input or input in both Python2 and Python3 with the semantics of Python2’s raw_input (aka the semantics of Python3’s input)

# 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
Answered By: George Birbilis

another way you can do it like this, by creating a new function.

import platform
def str_input(str=''):
    py_version = platform.python_version() # fetch the python version currently in use
    if int(py_version[0]) == 2:
       return raw_input(str) # input string in python2
    if int(py_version[0]) == 3:
       return input(str) # input string in python3

how to use:

str_input("Your Name: ")

I use this when I want to create scripts and inputs that can be run in python2 and python3

Answered By: Pausi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.