0

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))
1
  • 1
    why are you calling int on a variable called name and then casting to str? Commented Sep 21, 2015 at 19:15

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

im new to Python can you tell me how i intigrate it into my script?
Where you call Aufgabe() in line 3, you should instead call function_table[Aufgabe]()
AufgabenNummer = int(input("Welche Aufgabe willst du öffnen?\n")) Aufgabe = "Aufgabe" + str(AufgabenNummer) function_table['Aufgabe1']() 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))
Welche Aufgabe willst du öffnen? 1 Traceback (most recent call last): File "C:\Users\Moritz\Desktop\Selber Programmiert\Python\Aufgaben.py", line 3, in <module> function_table['Aufgabe1']() NameError: name 'function_table' is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.