Previous post: https://codinghelp.site/wiki/python/5-python-if-statement/
The “ELIF” statement
The Elif keyword in python stands for “else if”. It is strictly used with the IF statement and in most cases, else statement. If the IF statement gets ran (expression is met) the “ELIF” statement will not get ran. You can have as many ELIF statements as you want but, either none or just one will get ran (one where the provided expression is met).
“ELIF” Statement Syntax
An IF statement must be before an ELIF statement. If the “IF” statement’s expression does not get met, python will check if ELIFs expression is met. You can have however many you want ELIF statements. Only one ELIF statement will get ran, I’ll explain better in this picture:
Here, the second ELIF statement will never get ran if the first ELIF statement gets ran, which it does.
Expressions in the elif statement are written like usual logical conditions from math:
Here, we are telling python to print “Banana is less than 5” if the banana variable value is less than 5, which it isn’t. If the banana isn’t less than 5, it should try to see if the banana variable value is equal to 8, which again, it isn’t. Finally, we are telling python to print “Banana is equal or higher than 10” if the banana variable value is equal or higher than 10, which it is!
Write a script using ELIF and IF statements where the user can input a number, then make python tell them if the number is higher or less than 10.
Write a script using two ELIF and an IF statement where the user can input a number, then make python tell them if the number is equal to 5, less than 5 or higher than 5.