In Python, a conditional allows you to make a decision. In its simplest form it is stated as follows:
if (cond): ... cond_body ...The expression cond is a Boolean expression that evaluates to either True or False. If the condition is True then the body of code associated with it gets executed. If the condition is False nothing happens, the excution is resumed from the statement following the if block.
If you wanted to execute something else when the condition is False then you would introduce an else part like so:
if (cond): ... if_body ... else: ... else_body ...Remember to indent properly to delineate the body of code associated with the if part from the body of code associated with the else part.
What if you did not want to do anything in the if part but only had code for the else part? Python has a statement called pass which as the name imples does nothing.
if (cond): pass else: ... else_body ...Normally this is not how you would program. You would reformulate the Boolean expression so that it evaluates to True for the else and use a single if to express the condition.
You can also have nested conditonals depending upon the situation. Here is an example of that structure:
if (cond1): ... if_1_body ... else: if (cond2): ... if_2_body ... else: ... else_body ...Python allows a simpler way of nesting conditionals. You can use the keyword elif that is a contraction of the words else and if. So that the above code can be rewritten as follows:
if (cond1): ... if_1_body ... elif (cond2): ... if_2_body ... else: ... else_body ...In the if-elif-else construct, Python will go through in order all the if and elif conditions. The body of the first condition that is True is executed and the remaining conditions are ignored even if they are True. If none of the conditions are True then body of else part gets executed.