dlpnewbie96 dlpnewbie96 - 2 months ago 8
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)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")

def dead(why):
print why
exit(0)


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

2) How does the variable
how_much
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

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.