#this is the only mastery with three topics since all of them relate to each other.#

 

This three pals work together to make our life easier and just like the while they work with conditions.

We use if, elif and else when we desire to perform different actions depending on the outcome of a certain conditions, or multiple of them for that instance.

First let’s start with If and else. If will perform an action once IF a condition is met, and we use the else as a complement for this if, this is because if the condition of the “if” is not met, then the program will have nowhere else to go and it will die. Using “else” we suggest a second option, an escape route, for the program to use when the condition for “if” is not met.

Now, the thing with while and if is that they give you only two options to choose from, vanilla or chocolate, that’s why we have the “elif” condition to help us out, with else we can add as many extra conditions as we desire, sparing us a lot of trouble.

As an example:

X=input (“write 1 or 2”)

If (x=1):

Print (“yes”)

Elif (x=2):

Print (“no”)

Else:

Print (“wrong answer”)

 

In here we are validating the answer given to us by the user, we give the program two specific conditions for pairing the value of x given to us by the user and an “escape route” in case that the value doesn’t fit in any of the two previous conditions.

First the program will get the value of x from the user, and it will pair it with each of the conditions, if the value provided by the user is equal to one then the program will print “yes”, and if I is not it will validate the second condition, in the case that the value is equal to two then the program will print “no”, last but not least, if the value given by the user is neither one or two, then the program will take the “escape route” and print “wrong answer”.

This conditionals can be paired with “While” to make a program that constantly evaluates the values given to it, allowing us to make programs that adapt to a changing value.

CC BY 4.0 “Triple kill”: If, Elif and Else by juansalvadorfernandez is licensed under a Creative Commons Attribution 4.0 International License.