+ 1

Why elif if just "if" works

Can someone explain why I should use "elif" instead just "if". For example this code just works as well for me and I don't understand why I need "elif" X=7 If x==5: print("five") If x==11: print("eleven") If x==7: print("seven") else: print("it's not 5, 7 or 11")

18th Oct 2019, 5:24 AM
Rein Jakobson
Rein Jakobson - avatar
5 Respuestas
+ 4
If you just use if the program will have to go through and check every if condition vs if you use if elif elif elif else, if one of the statements are true it'll skip the rest of the statements below in the block. Its saving time for the program, like processing and execution or something like that.
18th Oct 2019, 5:52 AM
Odyel
Odyel - avatar
+ 4
In addition to what Kilowac said, there are legitimate uses. Elif is evaluated when the first if-condition evaluates to false and you want to check for additional conditions
18th Oct 2019, 6:04 AM
Trigger
Trigger - avatar
+ 1
If there is so many if else then better solution is use switch case. It save time to execution because when any condition will true then it will go outside the switch case because of break statement. But in if else statement it check every condition so it will take time.
18th Oct 2019, 7:38 AM
A͢J
A͢J - avatar
0
if you use elif rather than if, you can be free of indentation erro, but if you use if statement, you should very careful about indentation.
3rd Dec 2020, 7:33 PM
Python123
Python123 - avatar
- 1
In a python program you can not use multiple if's, only one though. But with elif you can use them multiple times.
18th Oct 2019, 6:07 PM
Aron Mitchell
Aron Mitchell - avatar