«Triple kill»: If, Elif and Else

#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.

Publicado por: juansalvadorfernandez

Elegí estudiar ITE porque pienso que es una carrera versátil con la que se pueden lograr cosas muy interesantes. Aunque realmente no sé si alguna otra carrera me gustaría más, las personas terminan haciendo lo que les gusta, independientemente de la carrera que estudien. Si alguien me pregunta quien es mi héroe, sería mi padre, pues es una persona fuerte que en momento de necesidad sacó adelante a su familia, pagó los estudios de sus hermanos, es un profesionista que disfruta de su trabajo y que tiene metas fijas y aspira a ellas con todas sus fuerzas. Hace tiempo tocaba la flauta dulce e intenté aprender a tocar piano, teclado y guitarra. No me gusta el deporte. Realmente no tengo un autor ni un libro favorito, siento que me falta encontrar un tema o un estilo que realmente me guste.

Etiquetas, , , , , Deja un comentario

Deja un comentario