2

Since Python 2's raw_input was changed to just input for Python 3, I was wondering if there was a way to take input while accounting for both Python 2 and 3. I'm trying to write a script for both versions, and this input part is the only thing that's not working well.

I tried running just input with Py2, and this happens:

>>> a = input('Input: ')
inp: test
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    a = input('Input: ')
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

I saw a workaround to quote the input:

>>> a = input('Input: ')
inp: "testing test"
a
'testing test'

Is there a way to concatenate the quote to the beginning and end of the input? '"' + input('input: ') + '"' isn't working

simplycoding
  • 2,770
  • 9
  • 46
  • 91

2 Answers2

2

Probably not a good practice, but you can use a try block to test whether the raw_input() is being recognized (thus telling you whether you're on Python 2.x or Python 3.x):

try:
    a = raw_input('input: ')
except NameError:
    a = input('input: ')

I would use raw_input() to test because it's not accepted by Python 3.x and is what you expect to use in Python 2.x, so the input() will not trigger in Python 2.x.

I'm not an expert so I'm sure there are better suggestions.

@Chris_Rands' suggested dupe thread has a more elegant solution by binding input = raw_input so if you have multiple input(), you only need to try once.

r.ook
  • 13,466
  • 2
  • 22
  • 39
  • Like you said, not a great way to do it say in production, but totally fine for a small personal throw away script. – Mad Physicist Jan 09 '18 at 16:51
  • I'm very much a beginner myself, so what's best practice is still very much unknown to me. IMO having a script supported in both Python version seems like a weird idea anyhow. Personally I would have branched it into two versions and have another main.py check the version to decide which script to fire up. – r.ook Jan 09 '18 at 16:57
-1

This works for both Python 2 and 3.

from builtins import input
input("Type something safe please: ")
Joren
  • 3,068
  • 25
  • 44