Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
6 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 (106k 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 Dec 22, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...