Reputation: 59
I'm trying to make a text game in python that's basically about exploring a fake hard drive through a CMD line. I'm experimenting with having the different subfolders saved in the code as different subroutines. Long story short I'm trying to make it so that you can call a subroutine from a variable name? Does anyone know if this is possible in python 3.6.3? Here's a test program to show my concept. Can anyone get this to work?
def level1():
print("you have reached level 1")
def level2():
print("you have reached level 2")
lvl = int(input("go to level: "))
lvl = str(lvl)
level = str("level"+lvl)
level()
Thanks for any help, -Rees :)
Upvotes: 0
Views: 216
Reputation: 51683
Two possibilities come to mind:
simple check with if
... elif
.. else
def level1():
print("you have reached level 1")
def level2():
print("you have reached level 2")
while True:
lvl = input("go to level: ").rstrip()
if lvl == "1":
level1()
elif lvl == "2":
level2()
else:
print("Back to root")
break
Second one is using eval()
- this is dangerous. You can input arbritary python code and it will work (or crash) the program:
while True:
lvl = input("go to level: ").rstrip()
try:
eval("level{0}()".format(lvl))
except: # catch all - bad form
print("No way out!")
Read: What does Python's eval() do?
Upvotes: 0
Reputation: 7850
It can be done, but you don't want to do it that way. Instead, put your functions into a list or dict and call them from that.
levels = { 1 : level1,
2 : level2 }
lvl = int(input("go to level: "))
levels[lvl]()
Upvotes: 1