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
user5360562
-
1why are you calling int on a variable called name and then casting to str?Padraic Cunningham– Padraic Cunningham2015年09月21日 19:15:51 +00:00Commented Sep 21, 2015 at 19:15
1 Answer 1
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
Sign up to request clarification or add additional context in comments.
4 Comments
wpercy
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))
lang-py