+1 vote
2 views
in Python by (10.2k points)
edited by

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?

2 Answers

0 votes
by (10.9k points)
edited by

@Anvi, To replace a switch statement in Python use the following code:

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)

0 votes
by (107k points)

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)

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)
+3 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...