Difference between If and Elif

1

What is the difference between the two code snippets

if variavel < 10:
   variavel = 1
if variavel >= 10 and <15:
   variavel = 2
.
.
.
else 
   variavel = 0
if variavel < 10:
   variavel = 1
elif variavel >= 10 and <15:
   variavel = 2
.
.
.
else 
   variavel = 0
    
asked by anonymous 26.11.2016 / 12:01

2 answers

7

In this section if variable is less than 10, first it will be the value 1 and then the else of the second if will be 0 , this because they are two separated ifs:

if variavel < 10:
   variavel = 1
if variavel >= 10 and <15:
   variavel = 2
.
.
.
else:
   variavel = 0

Here the elif is part of the "logic" of the if , ie if the variable is less than 10 it will only set the variavel = 1 :

if variavel < 10:
   variavel = 1
elif variavel >= 10 and <15:
   variavel = 2
.
.
.
else: 
   variavel = 0

In short, elif is a condition of if along with else , it would be practically the same as doing this:

if variavel < 10:
   variavel = 1
else:
    if variavel >= 10 and <15:
       variavel = 2
    .
    .
    .
    else: 
       variavel = 0

Unlike other languages Python does not use {...} , this is because it works with indentation PEP 8 (although the translation of the word is something like "recuamento", we usually adapt it from English to "indentation", not that it is the correct way, but maybe you will hear a lot)

  

IMPORTANT NOTE: I believe this is wrong elif variavel >= 10 and <15: , correct would be elif variavel >= 10 and variavel < 15:

In other words, to set a if you will need the spaces (note that python3 no longer supports mixing tabs) on the following lines:

if ... :
    exec1
    exec2
    exec3

If you do this, exec3 will be out of condition:

if ... :
    exec1
    exec2
exec3
    
26.11.2016 / 12:13
2

If is used to check a condition and the elif is used to check another condition if the If condition is false. In the code there is not much difference, elif will ensure that that condition is checked if the If is false, different from the two If they are independent 'flows'.

    
26.11.2016 / 12:04