Reputation: 3535
When I make text adventures in python for my friends, I am constantly frustrated that I have to code the adventure upward since python reads code from top to bottom. For example:
def stage2():
def stage1():
def start():
Then so on and so forth.. Is there any way that I can make python read the code in a different way so that I can code text adventures from the top up?
Upvotes: 0
Views: 61
Reputation: 56654
You can write your functions in whatever order you like, so long as they are defined before they are called.
For instance,
def start():
print("Welcome to the adventure")
stage1()
def stage1():
print("You made it this far!")
stage2()
# if you called start() here,
# you would have an error when stage1() tries to call stage2(),
# because the interpreter doesn't know what a stage2 is yet.
def stage2():
print("Oops - you died.")
start()
works fine.
On the other side of things:
def test():
if True:
print("Yup")
else:
slartibartfast()
test()
runs fine because the interpreter never gets around to asking what a slartibartfast is ;-)
Upvotes: 4