+ 1
Why elif is used when if can solve the problem? ?
4 Réponses
+ 5
Use the number 5 and you see the problem with your code
+ 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")
+ 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.
+ 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")