Input function for Python2 and Python3

Lardmeister 2 Tallied Votes 219 Views Share

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))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
# 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.