In Python , why do we use the elif ? and what is it?

Question:

In Python , why do we use the elif ? and what is it ?
I was learning about the else if commands and stumbled upon the elif and confused about it

Asked By: Arnav

||

Answers:

It sounds as if you are familiar with an "Else if" statement. An "Elif" statement is the "Else if" version of python.

Take the following Java code:

if(1 < 2) {
  System.out.println("if statement");
} else if(3 > 4) {
  System.out.println("else if statement");
}

Would turn into the following Python code:

if 1 < 2:
  print("if statement")
elif 3 > 4:
  print("else if statement")
Answered By: Michael Gathara

Elif, short for else if, is the conditional statement that comes after the if statement. It has to follow a boolean logical statement. An if statement is the gateway that allows the codes to be executed only if the statement after the "if" or "elif" passes.

Answered By: Amalie Shi

If you are familiar with else if in other programming languages then it is the same as else if but if you don’t let me tell you.

Like if you have only one thing to check then you will only be going to use if else. eg. if the percentage is greater or equal to 40% then the student is pass else the student is fail.

if percentage >= 40:
    print("You are passed")
else:
    print("You are failed")

but in case you also give grades to students according to their marks then you need to use elif. eg. if percentage greater or equal 85 then A grade, if the percentage is greater or equal 65 and less than 85 then the B grade and for less than 65 C will be graded.

if percentage >= 85:
    print("A grade")
elif percentage >= 65:
    print("B grade")
else:
    print("C grade")

and for the above code, you might be wondering if a student gets 88 marks then the if condition is true but the elif is also true. So in the conditional statement if one condition is matched true then it will not check all other conditions.

Answered By: Shubham Sharma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.