0

I am making a script that takes a string input. However, I want this script to be independent of python 2.7 or python 3+.

For python 2.7 I write

name = raw_input("Enter your name: ")

For python 3+ I write

name = input("Enter your name: ") 

How can I write a single line of code that will be compatible with both the version ?

Yash
  • 510
  • 2
  • 6
  • 14

2 Answers2

1
# Python 2 and 3:
from builtins import input

name = input('What is your name? ')
assert isinstance(name, str)    # native str on Py2 and Py3
mtkilic
  • 1,213
  • 1
  • 12
  • 28
0

There is no way you could do this in a single line of code, but you could use the following:

try:
   input = raw_input
except NameError:
   pass

Now calling input will work as expected in both Python 2 and Python 3.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88