Fahad Nezam
Fahad Nezam

Reputation: 27

If-else statements Python

I was wondering why we write "elif", if we could just write "if" for a "elif" statement.

Just a question of curiosity, why do we write "elif e == (f + 10)" instead of just "if e == (f+10)"?

e = 20

f = 10

elif e == (f + 10):
    print("e is 10 more than f")

Why can't I replace the "elif" with "if" and tell me why that wont work if I replace with my adulation.

Upvotes: 0

Views: 938

Answers (3)

Indunil Aravinda
Indunil Aravinda

Reputation: 823

imagine you have to check multiple conditions. so in the if case, you can only check one condition. but with elif you can check multiple conditions.

if (x==1):
    print("x is one")
elif (x==2):
    print("x is two")
else :
    print("x is not valid")

In here we've checked whether x=1 or x=2 and wrote the code relevantly. I wrote the same code (print()) , but you could write whatever is necessary in each condition. That's the point of having it

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

elif always has to be after a if, elif is really:

  • a representation of else and if mixed together.

Usually people use it in a if then elif then else, it's really standing for:

  • if the first condition (with if) is incorrect, do this condition, if it is still incorrect, got to else and if there is no else, just don't do anything and exit condition.

P.S. after all i forgot to tell you that the code is invalid.

Upvotes: 1

LovelyBanter
LovelyBanter

Reputation: 54

‘elif’ stands for ‘else if’ so basically the reason why you wouldn’t simply just use an ‘if’ statement is because say you have an initial ‘if’ statement that the program passes through and satisfies the condition, it will not pass through to the ‘elif’ statement following. If you had two ‘if’ statements after another then both will be passed through.

However an elif statement must follow an if statement, unlike the way you’ve used in your example

Upvotes: 2

Related Questions