+ 5
What is the use of elif statements and is there any difference if we use only if and else statement rather than elif?
num = int(input()) if num == 1: print("One") if num== 2: print("two") if num==3: print("three") else: print("something else") Like this only if and else is there if I run this code for example I take 1 in the input so if condition 1 is true then the output should be one right? But when I'm running this code else statement is also running? Why is it like this and what if I use elif statement? Will it make any difference?
7 Answers
+ 7
Ok thankyou
+ 6
else statement is also running because there is no elif so
if num is 1 then
'One' and 'something else' also will be print because num is not 3 so that's why we have to use elif.
if num == 1:
elif num == 2:
elif num == 3:
else
print ('') #this will execute when all other cases will be false
+ 6
Ok👍
+ 5
In this code, the "else" statement belongs only to the third condition.
The "elif" operator is needed to reduce the code and its performance.
If "num" = 1, then the rest of the conditions will still be checked, and when using "elif" the check will be completed.
+ 4
if-elif stops at the first True branch. They work as a group and it behaves like a lazy search and stops when a True condition is encountered.
Multiple ifs goes through every branch.They are independent of each other.
Try this:
n = 9
print('using only if statements:')
if n%2!=0:
print('n is odd')
if n>0:
print('n is greater than 0')
print('using if-elif:')
if n%2!=0:
print('n is odd')
elif n>0:
print('n is greater than 0')
In the top part using only if statements, both will be printed.
In the bottom part using if-elif, only the if condition is printed even though the elif part is also True.
if-else saves time if most of your conditions is near the top of the group because the program does not have to evaluate all the statements if the True condition is encountered early on.
+ 2
Elif checks all the options and then as soon as it finds the true one it stops and prints it while if they are all false it prints nothing and if you add else that will be the option it will print if all are false as a clause.
while if you put if/else it is as if the program thought to choose one or the other way.
+ 2
Using `elif` instead of separate `if` statements allows you to create a chain of conditions that are evaluated sequentially. It ensures that only one block of code is executed based on the first true condition, making your code more efficient and concise. With separate `if` statements, each condition is evaluated independently, which can lead to unnecessary checks and multiple blocks of code being executed. `elif` simplifies and streamlines your code for handling multiple conditions.