Conditionals in Python
Conditionals in Python
statements in Python This is the syntax of a basic
statement:
If the condition is
, the code will run. Else, if it’s
, the code will not run. Here we have some examples: False Condition
The condition is
and the code is
. In this case, the condition is
, so there is no output. True Condition Here we have another example. Now the condition is
:
The output is:
Code After the Conditional Here we have an example with code that runs after the conditional has been completed. Notice that the last line is not indented, which means that it doesn’t belong to the conditional.
In this example, the condition
is
, so the first print statement doesn’t run but the last print statement runs because it is not part of the conditional, so the output is:
However, if the condition is
, like in this example:
The output will be:
Examples of Conditionals This is another example of a conditional:
In this case, the output will be:
But if we change the value of
:
There will be no output because the condition will be
.
statements in Python We can add an
clause to the conditional if we need to specify what should happen when the condition is
. This is the general syntax:
Let’s see an example with the
clause: True Condition
The output is:
When the condition of the
clause is
, this clause runs. The
clause doesn’t run. False Condition Now the
clause runs because the condition is
.
Now the output is:
statements in Python To customize our conditionals even further, we can add one or more
clauses to check and handle multiple conditions. Only the code of the first condition that evaluates to
will run. First Condition True
We have two conditions
and
. Only the code block from the first condition that is
from top to bottom will be executed. In this case, the output is:
Because the first condition is
:
. Second Condition True If the first condition is
, then the second condition will be checked. In this example, the first condition
is
but the second condition
is
, so the code that belongs to this clause will run.
The output is:
All Conditions are False If all conditions all
, then the
clause will run:
The output will be:
Multiple elif Clauses We can add as many
clauses as needed. This is an example of a conditional with two
clauses:
Each condition will be checked and only the code block of the first condition that evaluates to
will run. If none of them are
, the
clause will run.
S.Schins BASICS
Python Basics Examples