Start New Discussion within our Software Development Community

String input has changed from Python2's raw_input(prompt) to Python3's input(prompt). The old Python2 numeric input(prompt) has gone away with Python3, all input is now string input. The snippet shows a few lines you can add to your program such that you only need to use input(prompt). This makes your code usable for both versions of Python.

Python2 coders have always been discouraged to use numeric input(), since it uses raw_input() and eval() internally. The unprotected eval() function can accept OS commands that can delete your disk.

# Python2 uses raw_input() for strings
# Python3 uses input() for strings

# ----------------------------------------------
# add these few lines near the start of you code
import sys
# make string input work with Python2 or Python3
if sys.version_info[0] < 3:
    input = raw_input
# ----------------------------------------------

# test ...
# now you can avoid using raw_input()
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# if you expect a float input, use float(input(prompt_str))
print("%s you are %d old" % (name, age))
# another way ...
# make string input work with Python2 or Python3
try:
    input = raw_input
except:
    pass

Now just use input() in your Python2 or Python3 code.

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.