dlpnewbie96 dlpnewbie96 - 1 year ago 78
Python Question

Variable scope in python code

from sys import exit

def gold_room():
print "This room is full of gold. How much do you take?"

choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
dead("You greedy bastard!")

def dead(why):
print why

1) How does the
method is called inside
method as the definition of
method is below the calling statement?

2) How does the variable
accessed outside of its scope? It was declared and initialized inside the indented block -

if "0" in choice or "1" in choice:
how_much = int(choice)

And according to my understanding, its scope should be ended here in this block. Then how it is used further in this condition -
if how_much < 50

Answer Source

There is no "dead" method built into Python. The reason why the interpreter tells you that it is not defined is because you haven't defined it.

Python does not have block scope. Variables defined inside a function are visible from that point on, until the end of the function.

edit after the first question was changed It doesn't matter in which order the functions are defined, as long as they are both defined at the time they are called. Presumably, you have some code at the end of that module which calls gold_room, after both functions are defined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download