Python Python Basics Types and Branching If, Else and Elif

Why not use If instead of using Elif

^^^

3 Answers

It simply prevents your other if-statements from being checked against.

Example: Let's assume you have a variable containing an age of 18 and you are checking if the person is an adult or still a child.

Using only if statements...

age = 18

if age < 21:
   print("You are a child")
if age >= 21:
   print("You are an adult")
else:
   print("The age must be a positive integer!")

...will make the person an adult and a child at the same time.

But elif...

if age < 21:
   print("You are a child")
elif age >= 21:
   print("You are an adult")
else:
   print("The age must be a positive integer!")

...will define the person only as a child.

Bonus: To achieve the same result just with if and else, it would look like this:

if age < 21:
   print("You are a child")
else:
  if age >= 21:
    print("You are an adult")
  else:
     print("The age must be a positive integer!")

The more checks you are implementing, the more levels of indentation you will get, wich makes it not that easy to handle. Sometimes referred to as 'Pyramid of Doom'.

Richard Li
Richard Li
9,746 Points

I think you mean that age variable in the first double if condition will be checked twice by child and adult and based on the syntax it will return a child and The age must be a positive integer at the same time.

Colton Ehrman
Colton Ehrman
241 Points

Not sure what you are asking without any context, but elif allows you to have multiple conditions in a single waterfall like structure that flows down each conditional and executes the first one that is true.

If you only have an if statement, more complex conditions would not be usable, or extremely hard to implement.

Also, because it prevents the following elif-statements from being checked against, the computer technically runs the script faster since it doesn't have to check any elif statements that come after the first true one. This will matter when you write longer code with more if statements.

BTW, Richard Li's correction about Sebastian Rother's example was correct.