Wednesday, 23 August 2017

Replacements for switch statement in Python?





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?


Answer



You could use a dictionary:




def f(x):
return {
'a': 1,
'b': 2,
}[x]

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...