Don't else if statements to the same thing as multiple if statements? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Don't else if statements to the same thing as multiple if statements?

On a school physics project we used Vpython and I was coding the boundaries of a basketball hoop so the ball bounces off the hoop. There I used inside a while loop, lots of if's statements and it worked. So if an if statement was false, it moved onto the next if statement and if it was true, it did what I told it to and once done, it moved onto onto the next of statement. Never had to use else statements , or else if statements. Just wondering what are the else if statements used for.

2nd Jun 2017, 5:19 AM
iiShadowii
iiShadowii - avatar
4 Answers
+ 3
That has mainly to do with whether the different cases are naturally self-excluding. If they're so, you could use only "if" statements. For example: if (age >= 65) { do senior things; } if (age < 65 && age >= 18) { do adult things; } if (age < 18) { do baby things; } But if the cases you're evaluating are not self-excluding, there could be a difference. Compare: if (age > 18) { go skaterolling; } if (has_a_pet == true) { go walk with your pet; } with if (age > 18) { go skaterolling; } else if (has_a_pet == true) { go walk with your pet; } In the first case, if you're older than 18 and have a pet, you'll perform both actions, but in the second case you'll only perform the first one.
2nd Jun 2017, 5:30 AM
Álvaro
+ 4
@aivaro: it's not doing the same. in your example the Programm would still check every if statement eventhough they are exclusive
2nd Jun 2017, 6:21 AM
Thanh Le
Thanh Le - avatar
+ 3
if a case is true it will go inside the if statement and won't go check the else statement anymore. much efficient. with multiple if statement it will check every one of the if statement. not good for performance.
2nd Jun 2017, 5:21 AM
Thanh Le
Thanh Le - avatar
0
Oh so it's for preformace, like a shortcut. Thx alot! ^-^
2nd Jun 2017, 5:24 AM
iiShadowii
iiShadowii - avatar