On 12/07/13 10:44, 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:
When you assign to a name *anywhere* inside a function, Python treats that name
as a local variable regardless of whether it is before, or after, the
assignment. So unlike the language Lua, you can't read a global variable, then
create a local variable of the same name in the same function.
In your case, the fix is to pull the renaming of input out of the function, so it is performed once
only, when the module first begins to run, instead of every time you call the function. Put the
renaming code at the top of the module, after the "import sys", then just unconditionally
use "input" inside the function.
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
The rules for local variables are rather more complicated in Python 2 and it
may be that you're somehow slipping through the cracks.
--
Steven
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor