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))
rescdsk
8,9254 gold badges39 silver badges32 bronze badges
asked Sep 21, 2015 at 19:05
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.

chepner
538k77 gold badges595 silver badges747 bronze badges
answered Sep 21, 2015 at 19:11
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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