Replacements for switch statement in Python

0 votes
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
May 29, 2018 in Python by charlie_brown
• 7,710 points
227 views

1 answer to this question.

0 votes

You could use a dictionary:

def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
answered May 29, 2018 by aryya
• 7,440 points

Related Questions In Python

0 votes
2 answers

Replacements for switch statement in Python?

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

answered Feb 9 in Python by Soham
• 9,670 points
231 views
0 votes
0 answers

Replacements for switch statement in Python?

I want to write a function in ...READ MORE

Apr 22 in Python by Edureka
• 12,390 points
60 views
0 votes
0 answers

Replacements for switch statement in Python?

I want to create a Python function ...READ MORE

Sep 21 in Python by Samuel
• 460 points
72 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,100 points
538 views
0 votes
1 answer

How to write inline if statement for print in Python?

Inline if-else expression must always contain the else ...READ MORE

answered Dec 4, 2018 in Python by Nymeria
• 3,560 points

edited Dec 6, 2018 by Nymeria 15,639 views
0 votes
1 answer

Unique identification for data items in Python

Try the UUID module of Python. For example, ...READ MORE

answered Apr 17, 2018 in Python by Nietzsche's daemon
• 4,260 points
616 views
0 votes
1 answer

Slice notation in Python for string reversal

The slice notation is [start:end:step]. Step = ...READ MORE

answered Apr 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
306 views
0 votes
1 answer

What is the flow control for “continue” in python?

This is the way "continue" statement works! You ...READ MORE

answered Jul 16, 2018 in Python by Priyaj
• 58,100 points
327 views
0 votes
1 answer

Can someone explain the behaviour of increment and decrement operators in python

down voteaccepted ++ is not an operator. It is ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,440 points
1,107 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,440 points
10,077 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