user5360562
user5360562

Reputation:

Function name as string

I got three functions, named Aufgabe[1,2,3]. I want to make it so that if someone enters in the console "1" Aufgabe1 gets triggered and so on. Is it possible to do?

AufgabenNummer = int(input("Welche Aufgabe willst du öffnen?\n"))
    Aufgabe = "Aufgabe" + str(AufgabenNummer)
    Aufgabe()

def Aufgabe1():
    zahl1 = int(input("Erste Zahl...?\n"))
    zahl2 = int(input("Zweite Zahl...?\n"))
    print (str(zahl1) + "+" + str(zahl2) + "=" + str(zahl1+zahl2))

def Aufgabe2():
    for i in range(0,11):
        print(i)

def Aufgabe3():
    name = int(input("Hallo wie heißt du?\n"))
    print ("Hallo" + str(name))

Upvotes: 0

Views: 77

Answers (1)

Chad S.
Chad S.

Reputation: 6631

The best way to do this is to maintain a dictionary of name/function pairs:

function_table = {
   'Aufgabe3' : Aufgabe3,
   'Aufgabe2' : Aufgabe2,
   'Aufgabe1' : Aufgabe1,
}

Then call the appropriate function by looking it up in the table

function_table['Aufgabe1']()

This allows you finer control over the mapping of inputs to functions allowing you to refactor freely without changing your program interface.

Upvotes: 7

Related Questions