[Tutor] renaming input works intermittently
Peter Otten
__peter__ at web.de
Fri Jul 12 08:34:11 CEST 2013
Jim Mooney wrote:
> When I tried a simple rename of input, it worked - in python 2.7 and
> python 3.3
>
> import sys
> if int(sys.version[0]) < 3:
> input = raw_input
>
> x = input('type something ')
> print(x) # this works in both Py versions
>
> But when I tried that in my numbers program, I got an error:
> UnboundLocalError: local variable 'input' referenced before assignment
> for the below:
>
> try:
> if int(sys.version[0]) < 3:
> input = raw_input
> numbers_str = original = input('Enter a positive'
> 'integer, space separated if desired.') # error occurs here
>
> Oddly, the error only occurs in Python 3.3 - the above works in Python 2.7
>
> Here it is, where I run it from the dos box. Fails in Py3 on the first
> run, works in Py2 on the second run
If you want to assign inside a function you can just pick an unused name:
def foo():
if sys.version_info.major < 3: # sys.version_info[0] to support
# versions below 2.7
safe_input = raw_input
else:
safe_input = input
numstr = safe_input("Enter a positive integer: ")
...
Personally I prefer to test for a feature rather than the version:
def bar():
try:
safe_input = raw_input
except NameError:
safe_input = input
numstr = safe_input("Enter a positive integer: ")
...
More information about the Tutor
mailing list