+ 2
How to switch?
Hello Pythoneers! I am trying to write a program for ATM that accepts from user a choice of operation and executes an operation, which is basically a method. As we know there is no switch case in Python. SO how to handle it without it? As piece of script you can find below: https://code.sololearn.com/cWH9ofLI40Ze
12 Respostas
+ 4
# Simply chain 'if' and 'elif' (else if) statements:
if choice == 1:
print('choice 1')
elif choice == 2:
print('choice 2')
elif choice == 3:
print('choice 3')
elif choice == 4:
print('choice 4')
# or you can define a dict (or list in case of continuous numeric keys) containing function to execute:
def onchoice1():
print('choice 1')
def onchoice2():
print('choice 2')
def onchoice3():
print('choice 3')
def onchoice4():
print('choice 4')
choices = { 1: onchoice1, 2 : onchoice2, 3 : onchoice3, 4 : onchoice4 }
choices[choice]()
+ 4
hello Saidamamad brother ! i am from tajikistan do you have viber or imo
+ 2
I did this task using C# once, but I need to learn Python now. It is a little bit confusing for me (
+ 2
# Lambda are useful to define short functions, so in such case as my examples, lambda are useful to avoid defining named function.
# On the other hand, in your last example lambdas are used only to define a call to another function: you could do better with:
return { 1 : ATM.checkBalance,
2: ATM.withdraw,
3: ATM.deposit,
4: ATM.exitProgram,
}.get(choice,ATM.errorOccured)()
+ 2
Practice, practice and practice again is the key... with curiosity: at each new problem to solve, you will search solutions, reading stuff, discovering new language features, and so step by step you will get more ideas for next problems to solve ;)
+ 2
Thank you very much!!! đ
+ 1
@visph thanks a lot! That one works! I did similar to that but in dictionary I wrote the parantheses along with the method name, so when the program run, the methods in the dictionary are executed đ which is unwanted.
choices[choice] () is amazing trick! đđ
+ 1
And I found a tutorial in youtube, which shows a good way also by defining a class method:
@classmethod
def operation(cls, choice):
return{ 1: lambda: ATM.checkBalance(),
2: lambda: ATM.withdraw(),
3: lambda: ATM.deposit(),
4: lambda: ATM.exitProgram(),
}.get(choice,lambda: ATM.errorOccured())()
while(True):
try:
choice = int(input('Operation mode: '))
except:
ATM.errorOccured()
continue;
ATM.operation(choice)
+ 1
It use a temporary dict with lambda functions under the hood ;)
Use of lambda could be a good idea (depending on context), but use of temporary litteral dict is not really, even if the lack of efficiency doesn't have a real impact in almost contexts ^^
0
So using lambda should be avoided in this case? Didn't get you well :(
0
Thank you very much, @visph! I am very week for these kind of tricks :( I don't know how to get like these ideas for problem solving :)
0
it is corret