Python Switch construct

0 votes
Is there a switch statement in Python just like there is one in C language?
Apr 19, 2018 in Python by onoff
636 views

1 answer to this question.

0 votes

You can use the python dictionary for this purpose:

def switch(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 10)    # 10 is default if x not found
...
switch('b')

Check out the docs for the dict.get() here: https://docs.python.org/3.6/library/stdtypes.html#dict.get

answered Apr 19, 2018 by Nietzsche's daemon
• 4,260 points

Related Questions In Python

0 votes
1 answer

Replacements for switch statement in Python?

You could use a dictionary: def f(x): ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,460 points
732 views
0 votes
1 answer

What is the Python equivalent for a case/switch statement?

if x == 'a':  # Do the ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 58,020 points
961 views
0 votes
2 answers

Replacements for switch statement in Python?

The recommended path for Python 3.10 which ...READ MORE

answered Feb 9, 2022 in Python by Soham
• 9,710 points
864 views
0 votes
1 answer

To simulate construct of other language does Python have a ternary conditional operator?

You can index into a tuple: (falseValue, trueValue)[test] test needs ...READ MORE

answered Oct 15, 2018 in Python by findingbugs
• 4,780 points
655 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,441 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,077 views
+4 votes
6 answers

Does Python have a ternary conditional operator like C does?

Yes, the syntax is: a if condition else ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
2,487 views
+4 votes
6 answers

Substring search in Python

Use the "in" operator in python" if "substring" ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
1,310 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP