This notion is one of the most important in programming. The idea is to say that if such a variable has such a value then do that if not that.
Take an example, we will give a value to a variable and if this value is greater than 5, then we will increase the value by 1
>>> a = 10 >>> if a > 5 : ... a = a + 1 ... >>> a 11
What if the value was less than 5?
>>> a = 3 >>> if a > 5 : ... a = a + 1 ... >>> a 3
Note that if the condition is not met, the instructions in the conditional structure are ignored.
If else condition
It is possible to give instructions whatever the possible choices with the keyword else
.
>>> a = 20 >>> if a > 5 : ... a = a + 1 ... else : ... a = a - 1 ... >>> a 21Let's just change the value of variable a :
>>> a = 3 >>> if a > 5 : ... a = a + 1 ... else : ... a = a - 1 ... >>> a 2
Elif condition
You can add as many precise conditions as you want by adding the keyword elif
, a contraction of "else" and "if", which could be translated as "otherwise".
>>> a = 5 >>> if a > 5 : ... a = a + 1 ... elif a == 5 : ... a = a + 1000 ... else : ... a = a - 1 ... >>> a 1005In this example, we have used the same as the previous ones but we have added the condition "If the value is equal to 5" what happens? Well we add 1000.
Possible comparisons
It is possible to compare elements:
== equal to ! = different from (also works with) > strictly greater than > = greater than or equal to <strictly less than <= less than or equal to
How do conditional structures work?
The if, elif, and else keywords seek to know if what is being submitted to them is True
. In English True means "True". So if the value is True, the instructions regarding the condition will be executed.
How do you know if the value that you submit to the interpreter is True? It is possible to see it directly in the interpreter.
Let's ask python if 3 equals 4:
>>> 3 == 4 False
He will kindly answer you that it is False
, that is to say that it is false .
Now we are going to give a value to a variable and we will ask it if the value corresponds to what we expect.
>>> a = 5 >>> a == 5 True
AND / OR
It is possible to refine a condition with the key words AND
which means " AND " and OR
which means " OR ".
For example, we want to know if a value is greater than 5 but also less than 10:
>>> v = 15 >>> v > 5 and v < 10 False
Let's try with the value 7 :
>>> v = 7 >>> v > 5 and v < 10 True
For the result to be TRUE
, both conditions must be met .
Now let's test the condition OR
>>> v = 11 >>> v > 5 or v > 100 True
The result is TRUE
because at least one of the two conditions is met .
>>> v = 1 >>> v > 5 or v > 100 False
In this case no condition is met, so the result is FALSE
.
Chain comparators
It is also possible to chain comparators:
>>> a , b , c = 1 , 10 , 100 >>> a < b < c True >>> a > b < c False
No comments:
Post a Comment