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
23 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 ariaholic
• 7,320 points
16 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
• 56,120 points
47 views
0 votes
1 answer

Replacements for switch statement in Python?

If you'd like defaults you could use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 56,120 points
14 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,730 points
21 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
24 views
+4 votes
6 answers
+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
70 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
66 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.