update 2021: In version 3.10 of Python the construction is being introduced match/case
, which can also function as the switch/case
of C, although it is not the main objective. Check in: How Python structural matching (match declaration) works?
Original response
Python does not have a construction named after switch
(and the complementary case
) - for the simple reason that the way the if
(and the complementary elif
and else
) can do the same job - with some advantages.
Even in languages that derive the syntax of C, which has the switch
, nowadays it is just "one more way to do the same thing" - that would be feasible with chaining if
and else if
s. The historical reason for a separate construction is that in the time when computers had much less resources than today (on the order of 1 million times less memory) - the switch-case was a way for the programmer to make explicit to the C compiler a "jump table" which would generally be more efficient than a sequence of if
s when turned into native code. Compilers (and even Cpus) have for decades incorporated enough otmization strategies to make this redundant.
But back to Python, the simplest and most direct way to do what you want is simply to:
for elemento in lista:
if elemento == 1:
funcao1()
elif elemento == 2:
funcao2()
...
else:
funcao_nao_encontrado()
Realize that unlike what happens with the switch
in any language, the "true or false" expression of the if’s sequence is not limited to comparing equalities - you can make any comparison, call other functions, etc... - as Python has the interval comparison shortcut notation - the same one we use in math - which translates a < x < b
for a < x and x < b
- you can easily incorporate intervals into your comparisons:
...
elif 2 <= elemento < 5:
funcao_para_numeros_medios()
elif elemento == 5:
...
If it seems to write the comparisons of if
is a lot, - if all you want to do for each option is to call a separate function, it is possible to use the advantage that Python functions are objects that can be passed as parameters and used in other data structures - in this case, you can simply create a dictionary where the keys are the numbers you would put in the case
and the values the functions you want to call:
def funcao1():
...
def funcao2();
...
...
funcoes = {
1: funcao1,
2: funcao2,
...
}
for elemento in lista:
funcoes[elemento] ()
Ready - that last line calls the proper function, which was retrieved from within the dictionary I called funcoes
above.
What is a "conditional loop for each value"?
– jsbueno
Python doesn’t have the cosponsor
switch
- you must useif
andelif
– jsbueno
type i want to read each value of my list eg if the value is 1 I run a function, now if it is 2 I run another function think and that
– user45474