switch
in python
, type I have a list with ten values lista = [1,2,3,4,5,6,7,8,9,11]
now I want to access this list value by value and create a loop conditional for each value how and what do I do? I appreciate your help.
switch
in python
, type I have a list with ten values lista = [1,2,3,4,5,6,7,8,9,11]
now I want to access this list value by value and create a loop conditional for each value how and what do I do? I appreciate your help.
switch
(and the complement case
) - for the simple reason that the way if
(and the elif
and else
complements) can do the same work - with some advantages.
Even in languages that derive the syntax of C, which has switch
, nowadays it's just "one more way to do the same thing" - that would be doable with concatenation of if
and else if
s. The historical motif of having a separate construct is that at a time when computers had much less resources than today (of the order of 1 million times less memory) - the switch-case was a way for the programmer to explicitly explain to the C compiler a " table of jumps "which would generally be more efficient than a sequence of if
s when transformed into native code. For a few decades, compilers (and even CPUs) have incorporated enough computing strategies to make this redundant.
But back to Python, the simplest and most straightforward way to do what you want is simply:
for elemento in lista:
if elemento == 1:
funcao1()
elif elemento == 2:
funcao2()
...
else:
funcao_nao_encontrado()
Note that unlike what happens with switch
in any language, the expression "green or false" in the if's sequence is not limited to comparing equalities - you can do any comparison, call other functions, and so on. .. - as Python has the interval comparison shortcut notation - the same one we use in math - which translates a < x < b
to a < x and x < b
- you can easily incorporate ranges in your comparisons:
...
elif 2 <= elemento < 5:
funcao_para_numeros_medios()
elif elemento == 5:
...
If it seems that writing the% cos_% comparisons is a big deal, - if all you want to do for each option is to call a separate function, you can use the advantage that functions in Python are passable objects 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 if
and the values the functions you want to call:
def funcao1():
...
def funcao2();
...
...
funcoes = {
1: funcao1,
2: funcao2,
...
}
for elemento in lista:
funcoes[elemento] ()
Done - this last line calls the appropriate function, which was retrieved from within the dictionary I called case
above.
Python does not have a switch
function as far as I know, if this is crucial to the program you can use this package: ( link ) which is similar to C, C ++, Java, etc. But with minor differences.
Edit: How did I not think of it while reading? You can also (apparently) implement C and C ++ in Python ( link )