2

I initialized rate as a global var:

import os, sys
rate=30

def foo():
    print('#########rate:', rate)
    if False:
        rate=int(sys.argv[2])


foo()

but when running the script, I get the following error:

Traceback (most recent call last):
  Line 10, in <module>
    foo()
  Line 5, in foo
    print('#########rate:', rate)
UnboundLocalError: local variable 'rate' referenced before assignment

although the if False: rate=int(sys.argv[2]) statement is not executed, it seems has some influence, is there some python rules explains this?

1 Answer 1

3

You should declare rate as global:

import os, sys
rate=30

def foo():
    global rate # <----
    print('#########rate:', rate)
    if False:
        rate=int(sys.argv[2])


foo()

If there is assignment to a varaint (without global declaration), it is treated as local variable.

Sign up to request clarification or add additional context in comments.

3 Comments

Might be worth explaining why
why it becomes local even that expression is not executed?
@zhangxaochen, If there is assignment to a varaint (without global declaration), it is treated as local variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.