Python:用户输入与版本无关

Python: User input irrespective of the version

我正在制作一个接受字符串输入的脚本。但是,我希望此脚本独立于 python 2.7 或 python 3+。

为了python2.7我写

name = raw_input("Enter your name: ")

为了python 3+ 我写

name = input("Enter your name: ") 

如何编写一行代码同时兼容两个版本?

您无法在 单行 代码中执行此操作,但您可以使用以下代码:

try:
   input = raw_input
except NameError:
   pass

现在调用输入将在 Python 2 和 Python 3 中按预期工作。

# Python 2 and 3:
from builtins import input

name = input('What is your name? ')
assert isinstance(name, str)    # native str on Py2 and Py3