Back
I want to write a program which returns different values for different input,it can be easily done using switch case but Python doesn’t seem to have switch cases so, can anyone suggest me some alternative?
@Anvi, To replace a switch statement in Python use the following code:
def f(x): return { 'p': 9, 'q': 5, }[x]
def f(x):
return {
'p': 9,
'q': 5,
}[x]
Alternatively, you can also use:
def f(x): return { 'p': 9, 'q': 5 }.get(x, 0)
'q': 5
}.get(x, 0)
You can use the below-mentioned code:-
result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2}[value](x)
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
You can use the following video tutorials to clear all your doubts:-
Be a Python Expert. Enroll in Python Programming Course by Intellipaat
31k questions
32.8k answers
501 comments
693 users