0
i dont understand the difference between if and elif
5 Respuestas
+ 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
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
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
0
Yeah guys, but can't i just use if to do all that ?
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:
.............