How do I use raw_input in Python 3?

Viewed 1030820

In Python 2:

raw_input()

In Python 3, I get an error:

NameError: name 'raw_input' is not defined

9 Answers

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

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

Related