Why elif is used when if can solve the problem? ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why elif is used when if can solve the problem? ?

https://code.sololearn.com/cmB91M73VbWY/?ref=app

24th Jun 2019, 7:10 AM
Demon King
Demon King - avatar
4 Answers
+ 5
Use the number 5 and you see the problem with your code
24th Jun 2019, 7:17 AM
Lexfuturorum
Lexfuturorum - avatar
+ 5
#This piece of code prints only "smaller than 10" and it does not print "odd number" num = 7 if num < 10: print ("smaller than 10") elif num < 5: print ("smaller than 5") elif num % 2 != 0: print ("odd number") print("end of 1st piece") #This piece of code prints "smaller than 10" and it also prints "odd number" num = 7 if num < 10: print ("smaller than 10") if num < 5: print ("smaller than 5") if num % 2 != 0: print ("odd number") print ("end of 2nd piece")
24th Jun 2019, 7:31 AM
Usama Bin Mamun
Usama Bin Mamun - avatar
+ 1
num = 5 if num == 5: print("Number is 5") num = 11 if num == 11: print("Number is 11") num = 7 if num == 7: print("Number is 7") else: print("Number isn't 5, 11 or 7") #Number is 5 #Number is 11 #Number is 7 If you replaced the 2 if statements with elif statements, if for example (if num == 11) was True, then you would make sure, that the following elif and else statements would not be tested or ran.
24th Jun 2019, 8:10 AM
Seb TheS
Seb TheS - avatar
+ 1
Here is an example, where elif statements make this code a little shorter: x = True y = False if x and y: print("Both x and y are True") #If x and y was True, following elif statements would not be tested or ran. #Because we know that if the next elif statement is tested, we would know, that atleast one of x and y is False, we do not need to use elif (x and not y) and elif (not x and y) when we can just try: elif x and elif y. That's logical thinking. elif x: print("Only x is True") elif y: print("Only y is True") else: print("Both x and y are False")
24th Jun 2019, 8:21 AM
Seb TheS
Seb TheS - avatar