I'm trying to do exercise 36 (spend a week making a text-based game) in "Learn Python The Hard Way".
Want I want to do is run func_1(x)
and then have that run func_x(0)
. I can't figure out how to do that though. I've tried just writing func_x(0)
but it returns a NameError: Global name 'func_' is not defined
. I also tried func + x + (0)
and I get the same NameError
. I thought maybe if I could peice the function's name together prior to calling it that would work so I did func = 'func_' + str(x) + '(0)'
and then tried room
but that just didn't do anything at all. When I print
it does return as func_x(0)
.
This is my code that I am trying to get the above to work in. n, x, o, y
were included for completeness. I removed the rest of the code to make this more concise and tested the below before posting to make sure everything else was still running fine.
import sys
from time import sleep
def in_room(r, n, x, o, y):
in_room = True
search_times = 0
while in_room == True:
action = raw_input("What would you like to do?:> ")
if action == 'search' and search_times < 1:
print (n, x, o, y)
search_times += 1
elif action == 'search' and 1 <= search_times:
print "There is nothing in the room."
elif action == 'go through right door':
in_room = False
elif action == 'go through left door':
in_room = False
elif action == 'look around':
room_r(0)
def room_1(state):
words ="""
You are in a dank room.
The walls are wet and the floor slimey.
There is a door to your left and right.
The door behind you closes.
"""
for char in words:
sleep(0.02)
sys.stdout.write(char)
sys.stdout.flush()
if state == 0:
return
in_room(1, 1, 6, 1, 6)
room_1(1)
I would use a list
to get the function you want to invoke:
funcs = [
func_0,
func_1,
func_2,
]
# Get the correct function
# x would need to be a number 0-2 in this case
func = funcs[x]
# Call the function
func(0)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments