global and loop control variable
Lorenzo Sutton
lorenzofsutton at gmail.com
Thu Jul 23 07:20:47 EDT 2015
On 23/07/2015 12:24, candide wrote:
[...]
>
> Now, global declaration has another restriction, as PLR explains:
>
> [https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement]
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Names listed in a global statement must not be defined as formal parameters
> or in a for loop control target,
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> What I understand is that the following is a must-not-code:
>
> # ---------------------------------------
> def f():
> global i
> for i in range(1,3):
> print(10*i)
>
> f()
> print(i)
> # ---------------------------------------
>
> But, the later code executes silently without any warning:
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 10
> 20
> 2
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> So my question is: what is the restriction about global as loop control variable the docs is referring to?
>
I think for situations like this one?
# ---------------------------------------
def f():
global temperature
for temperature in range(1,3):
print "In f temperature is:", temperature
temperature = 500
print "temperature is now", temperature
f()
print"temperature is now:", temperature
# temperature is now "broken"
if temperature <= 100:
print "Launching rocket"
else:
# this never happens
print "temperature too high! Aborting launch."
# ---------------------------------------
More information about the Python-list
mailing list