Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If vs. else if vs. else statements?

Are:

if statement:
if statement:

the same as

if statement:
elif statment:

and

if statement:
else statement:

the same? If not, what's the difference?

like image 683
Eed Avatar asked Nov 13 '13 06:11

Eed


People also ask

Should I use if or else if?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

What is the difference between if if else and if Elif else statement?

The first form if-if-if test all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive. Hope this answers your question!!!

What is the difference between ELSE and ELSE IF in C?

So as the default case handles all possibilities the idea behind else if is to split this whole rest into smaller pieces. The difference between else and else if is that else doesn't need a condition as it is the default for everything where as else if is still an if so it needs a condition.

What is if else if else statement?

If / Else / Else If conditional statements are conditional statements that have more than one condition. If the first condition is false, only then will the second condition will be checked. If the second one is also false, then the app will default to else or it will do nothing. Check out the diagram below.


2 Answers

No, they are not the same.

if statement:
if statement: 

If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.

if statement:
elif statment:

The second block will only execute here if the first one did not, and the second check is true.

if statement:
else:

The first statement will execute if it is true, while the second will execute if the first is false.

like image 66
Christian Stewart Avatar answered Oct 21 '22 10:10

Christian Stewart


The first one is different

if True:
    print 'high' #printed
if True:
    print 'low'  #printed

than the second

if True:
   print 'high' #printed
elif True:
   print 'low'  #not printed

and the third is invalid syntax

See tutorial.

like image 30
Paul Draper Avatar answered Oct 21 '22 10:10

Paul Draper