0

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 :)

Rees K
  • 59
  • 6
  • while you might be able to do this, you might want to think of other ways you can implement this. – Joe Mar 02 '18 at 19:23

2 Answers2

1

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]()
glibdud
  • 7,550
  • 4
  • 27
  • 37
0

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?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69