Functions continuing to ru after returning something?
Stefan Schwarzer
sschwarzer at sschwarzer.net
Tue Aug 31 17:16:10 EDT 2010
Hi,
On 2010-08-31 02:05, Bradley Hintze wrote:
> I may be having a brain fart, but is it at all possible to have a
> function first return a value then continue its calculation. Like this
> simple example:
>
> my_var = 5
> def my_function():
> return my_var
> my_var +=1
>
> This obviously won't work as written but is there a cleaver way around this.
At least in CPython 2.6.5 the above code results in
Traceback (most recent call last):
File "test.py", line 7, in <module>
my_function()
File "test.py", line 3, in my_function
return my_var
UnboundLocalError: local variable 'my_var' referenced before assignment
as soon as the function is called.
If you want to have the global my_var modified, you need
a "global my_var" statement in the function body.
Stefan
More information about the Python-list
mailing list