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!
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (3)
both
if
andelif
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:
Now here, the output will be:
first
Why? That's because when the if condition becomes
True
, we no longer need to check for theelif
condition (which is basicallyelse if
in C if you've coded in C).Now if the structure would've been this:
The output would've been:
first
second
That's because now we are checking for BOTH the
if
conditions.When you use
elif
withif
, you essentially bond them together such that only ONE OF THEM WILL EXECUTE (if none of them does, it's recommended to keep anelse
statement too).But when using multiple
if
s together, python will check for each condition, because they are essentially different and not bonded together.I hope that clears things out!
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!
Using of
elif
is needed when checks should be mutually exlusive.You might also want to look into
match .. case
operators:Some comments may only be visible to logged-in visitors. Sign in to view all comments.