yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

if-elif-else | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

We can use an if statement to control that a particular block of code only executes when the condition evaluates to true. But what if we want to do something else only when the condition evaluates to false? Well, we can add another if statement and try and construct a condition that's the exact opposite of the original condition. That's a bit annoying, and sometimes the opposite condition isn't obvious, or it's super long.

To save us the trouble, Python instead lets us use an else branch. We can stick an else branch onto the end of any if statement, and any instructions indented inside the else branch only execute if the corresponding if statement's condition evaluates to false. That makes the if branch and the else branch mutually exclusive. Based on the answer to the condition, the computer decides which of the two paths to take.

The Python syntax for an else branch is just the keyword else followed by a colon. Again, we use indentation to tell the computer which lines of code are inside the else branch. An else branch must always follow an if branch; otherwise, what are we taking the opposite of?

Let's trace that execution path. If the condition evaluates to true, as normal, the computer goes on to execute any instructions indented inside that if branch. When it's done, execution jumps to the next line of code that's indented outside of the conditional. If the condition evaluates to false, the computer skips the rest of the if branch and jumps to the else branch. Then it executes any lines of code that are indented inside the else branch. When it's done, it just continues execution with the next line of code indented outside of the conditional.

Note that this execution path with an else branch is different from this, where we just have that instruction indented outside of the if statement. Here, if the condition evaluates to true, we print "mobile layout." Then we jump outside of the conditional and print "desktop layout." If the condition evaluates to false, we skip the if branch, jump outside of the conditional, and print "desktop layout." Because the instruction is not indented, it's independent of the conditional; it always executes.

However, if we indent this instruction inside an else branch instead, we only print "desktop layout" if the condition evaluates to false. If the condition evaluates to true, we print "mobile layout" and skip the else branch.

What if we have more than two cases, like a mobile, tablet, and a desktop layout? We could try to construct three mutually exclusive conditions, or we can take advantage of a shortcut and use the elif branch. The elif, or else if branch, allows us to chain multiple conditions together, starting with the if branch. The computer evaluates each condition in order until it finds one that evaluates to true. Then it chooses that branch to execute.

Note that order matters here because the computer will stop checking other branches as soon as it finds one that evaluates to true. If instead, I put this condition first, the if branch would capture any screen widths that are smaller than 760. That means that if I have a mobile screen that, say, 300 pixels, it will get captured by this first case and print "tablet layout." The computer only ever chooses one branch; it doesn't print "mobile layout," even though that condition would have evaluated to true.

We can attach as many elif branches as we want to any if branch, and then we can optionally add an else branch at the end. So we can see what the computer's doing. Let's trace each possible execution path. If the first condition evaluates to true, then the computer chooses that branch and executes any instructions indented inside of it. Then it jumps to the next line of code outside of the conditional.

If the first condition evaluates to false, then the computer goes on to check the next condition. If the second condition evaluates to true, then the computer chooses this branch and executes any instructions indented inside of it. Then it jumps to the next line of code outside of the conditional.

If the computer checks the first condition and finds that it evaluates to false, then checks the second condition, and also finds that it evaluates to false, then it moves on to the else branch. Else branches don’t have a condition, so if the computer reaches it, it just runs. So we execute the instructions indented inside the else branch, and then we jump to the next line of code outside of the conditional.

So if you have multiple related conditions in your program, it's generally better to use a chained conditional with elif and else branches instead of several independent single-branch conditionals. Chained conditionals make programs easier to read because it makes the relationship between conditions obvious. It reduces bugs because we, as the programmer, don't have to worry about making sure all our conditions are mutually exclusive and cover all possible cases.

It saves the computer some work. With independent conditions, the computer doesn't know they're related, so it'll evaluate every single one, even if it's impossible for multiple of them to be true. With chained conditionals, we give the computer the hint that these are all mutually exclusive, so it knows it can stop evaluating as soon as it finds a branch that evaluates to true.

More Articles

View All
Surviving a Hippo Attack | Something Bit Me! | National Geographic
Deep beneath the surface of the Zambezi River in Zimbabwe, Africa, Kristen Yaldor is trapped in the jaws of a hippopotamus. As she struggles to free herself, the animal refuses to let go, ragdolling her back and forth. Hippos wouldn’t necessarily just dra…
If We Colonize the Moon, This Company Wants to Ship Our Stuff | Short Film Showcase
[Music] All good ideas start as crazy ideas, and then at some point, they occur. Then they become, “Why haven’t we been doing that all along?” We are right now in that transition for changing the way people think about the Moon. The Apollo missions were l…
Jamestown - Bacon's Rebellion
So, in the last video, we were talking about the system of labor in the Chesapeake area surrounding the Chesapeake Bay in the early English colonies in America. One thing that seemed a little bit strange there was that even though the first ship with ensl…
Character actions in stories | Reading | Khan Academy
Hello readers! Today it is a time for action. Yes, sound the horn of action, because today we’re going to be talking about character actions in stories. Understanding what characters do is key to your success as a reader. The way characters behave towards…
Why Do Cameras Do This? | Rolling Shutter Explained - Smarter Every Day 172
What’s up? I’m Destin. This is Smarter Every Day. Get your phone out. You see that little camera assembly there? Let’s take it out of the phone. Yep. That’s what it looks like. So here’s what we’re going to do. The first thing we’re going to do is pop th…
Charlie Munger's SCARY Inflation Warning (2022)
What makes life interesting is we don’t know how it’s going to work out. I think we do know we’re flirting with serious trouble. Inflation is at such high levels right now that those of us under the age of 40 have never even lived through a period of such…