i dont understand the difference between if and elif | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

i dont understand the difference between if and elif

25th Apr 2020, 7:47 PM
sofronis
sofronis - avatar
5 Answers
+ 1
Consider the following codes: #______________ score = 67 grade = ’fail' if score > 70: grade = 'A' elif score > 60: grade = 'B' elif score > 50: grade = 'C' print(grade) #outputs B #______________ score = 67 grade = ’fail' if score > 70: grade = 'A' if score > 60: grade = 'B' if score > 50: grade = 'C' print(grade) #outputs C Explanation: elif statement will only execute if previous if or elif statement is false. elif is like doing this if(condition): #do something else: if(elif condition): #do something else
25th Apr 2020, 9:32 PM
Ore
Ore - avatar
0
If first statement is true execute it elif second statement is true execute it else execute this statement This way you can check for many values if sometimes say value x is true,first statement will run ,if say value y is true ,second statement will run If none value is true else will run Using if allows you to check for only one condition
25th Apr 2020, 7:53 PM
Abhay
Abhay - avatar
0
Elif is just like a switch statement it checks a block of code if true it executes it if false it goes to the next statement if none are true the else statement which is compulsory is used while the if statement only checks one condition and determines whether it is true or not and returns the value
25th Apr 2020, 7:57 PM
Hansel
0
Yeah guys, but can't i just use if to do all that ?
25th Apr 2020, 8:45 PM
sofronis
sofronis - avatar
0
ok i will explain you. imagine 4 dors in front of you. each dor jave number 1,2,3,4 for example. end you know that behind the door you get some surprize, for each surprize for each door. so you think if i open the 1 door then i get surp1 else if i open door 2 i get.. else if i open door 3 i get ... else if i open door4( also for last door you can say just else since this door is last) according to imagination you can write if condition1: #somecode elif condition2: # some other cod3 elif condition3: # some other other code .......... .......... else: .............
25th Apr 2020, 8:49 PM
george
george - avatar