DEV Community

Shawn
Shawn

Posted on

Elif or If; that is my question.

Hello! I've recently started out with Python, and I want to know more about elif and if statements. I'm confused by which is more appropriate at one time so you can successfully speak to the computer. Could you give me some examples of when you would use elif over if and vice versa? Thank you DEV community!

Top comments (3)

Collapse
 
sanskari_patrick07 profile image
Prateik Lohani • Edited

both if and elif statements are used to check if a condition is true or not, but there is a subtle difference in usage.

Let's take the following structure:

s = "noice"
if(s[0] == "n"):
    print("first")
elif(s[1] == "o"):
    print("second")
Enter fullscreen mode Exit fullscreen mode

Now here, the output will be:
first

Why? That's because when the if condition becomes True, we no longer need to check for the elif condition (which is basically else if in C if you've coded in C).

Now if the structure would've been this:

s = "noice"
if(s[0] == "n"):
    print("first")

# Notice that this is an if instead of an elif
if(s[1] == "o"):
    print("second")
Enter fullscreen mode Exit fullscreen mode

The output would've been:
first
second

That's because now we are checking for BOTH the if conditions.
When you use elif with if, you essentially bond them together such that only ONE OF THEM WILL EXECUTE (if none of them does, it's recommended to keep an else statement too).

But when using multiple ifs together, python will check for each condition, because they are essentially different and not bonded together.

I hope that clears things out!

Collapse
 
shurwood_840b883d3a1ae4a2 profile image
Shawn

Oh! That makes a lot more sense! So putting elif and if statements together means that it's confusing replit and making it to where it doesn't understand what to print. That helps me a ton! Thank you!

Collapse
 
rudyryk profile image
Alexey Kinev

Using of elif is needed when checks should be mutually exlusive.

You might also want to look into match .. case operators:

match parameter:
    case pattern1:
        # code for pattern 1
    case pattern2:
        # code for pattern 2
Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.