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

if statements | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

We can use Boolean expressions to ask questions in our programs, but how can we branch control flow based on the answer? To do that, we need conditionals. Conditionals form the basis of selection; they allow the computer to decide which code to run depending on whether the answer to a specific question or condition is true or false.

The first piece of a conditional is the if statement. We start an if statement with the keyword if. Then we add our condition, which can be any Boolean expression. We always end this line with a colon because an if statement comes in two parts: this first part, which is the condition, and the second part, which is the instructions to run if that condition evaluates to true.

In Python, we indicate those instructions using indentation. Any lines of code immediately following that condition that are indented one level in are considered inside that if statement. If the condition evaluates to true, the computer will go on to execute all of the instructions indented inside the if statement in order. When it's done, it'll go on to execute the rest of the program as normal.

If the condition evaluates to false, the computer will skip all the lines of code that are indented inside that if statement. Instead, it'll jump directly to the next line of code that's outside of the if statement; that means the first line of code that is indented at the same level as that initial if.

Let's try an example. Here we have the Boolean expression num_orders == 10, which asks the question, "Is this the customer's 10th order?" We can then use this Boolean value in our if statement. We'll indent one print function call inside of the if statement and one outside. The one inside will only execute if it is the 10th order; that is, if the variable num_orders contains the Boolean value true.

We can also write this without the variable, where we just inline that whole Boolean expression in the if statement. Let's trace how the computer executes this. It starts with the first line and assigns the value 10 to the variable num_orders. Then it hits this if statement, so first, it evaluates the Boolean expression 10 == 10.

Since this evaluates to true, the computer will execute the lines of code indented inside of the if statement. First, it'll print "Your order is free," and then it'll assign the value zero to the variable num_orders. Then it just keeps moving through the rest of the program in order, so it'll print the value of num_orders, which is now zero.

Now, let's say instead num_orders was originally set to three. When the computer executes this program, it'll assign the value three to num_orders, evaluate the Boolean expression 3 != 10, which is false. Then, because it's false, we'll skip the lines of code indented inside the if statement. It'll jump to the next line of code outside, which is print(num_orders), so it'll print three.

Note that if we didn't indent the line of code num_orders = 0, it would be considered outside of the if statement. So, in the false case, num_orders would be set to zero, and then it would print zero. In the true case, we would print "Your order is free," then we would set num_orders to zero, and then we would print zero.

You can write if statements with any Boolean expressions as conditions, and you can put any and as many instructions as you want inside of them. With this conditional, I could make sure to only ask the follow-up question "Chicken or Tofu" if the user ordered Pad Thai because if they order the papaya salad, that question doesn't make sense.

Note that in most IDEs, we indent using the Tab key. Our standard lines of code should line up directly with the left margin; that is, there should be no spaces or indents before them. Lines of code indented inside of an if statement should be one tab key over. Getting the indentation right is crucial because this is the only way we can tell the computer which lines of code are inside the if statement and which are outside.

We need to be careful here, though, because now our control flow branches. If the user orders Pad Thai, this program works fine, but if the user orders something else, we get a name error. The variable protein is only defined inside the if statement. If the condition is false, this assignment statement doesn't execute, so the computer doesn't know a variable protein.

To fix this, we either need to make sure we're only accessing the variable protein inside the if statement, where we're guaranteed it exists, or we need to initialize the variable protein before the if statement, which guarantees that it's always defined. It's common in situations like this to initialize the variable to an empty or placeholder value like the empty string or "no protein."

Now there's no error on either possible path, whether the order is equal to Pad Thai or if it's not. Now that our control flow branches, when we run a program, we're only testing one of perhaps many possible paths of execution through the code. Just because it works for one case doesn't mean it works for the other, and it's up to us to test for that. Otherwise, it'll be our users who suffer when they're the first ones to find the bug.

More Articles

View All
The reason why your life is so boring and how to change it
You wake up tired. You work for long hours. You come back home and rather doing something you truly enjoy, you either pick up your phone and turn on Netflix and simply waste your time. You already know hitting the gym, reading a book, or going for a simpl…
Reporting measurements | Working with units | Algebra 1 | Khan Academy
In this video, we’re going to talk a little bit about measurement and the idea that you really can’t measure exactly the dimensions of something. And I know what you’re thinking: you’re like, well, no, of course, we can measure the dimensions of something…
This Is Why Discord Is Dangerous
On the 13th of April 2023, a 21 year old member of the U.S Air Force National Guard, Jack Tashira, was arrested on live TV for leaking classified documents. Tashira had shared classified information about the war in Ukraine with his Discord group, Thug Sh…
Limit of sin(x)/x as x approaches 0 | Derivative rules | AP Calculus AB | Khan Academy
What we’re going to do in this video is prove that the limit as Theta approaches zero of s of theta over Theta is equal to 1. So let’s start with a little bit of a geometric or trigonometric construction that I have here. This white circle, this is a uni…
The Second Great Awakening - part 3
Okay, so we’ve been talking about the Second Great Awakening and its context in early 19th century America. The Second Great Awakening was this period of religious revival that was kind of at its hot point in 1820 to 1840. In the last couple of videos, we…
How Would Warren Buffett Invest a Small Sum of Money?
I’m Michael Zenger from Danvers, Massachusetts. That’s the town who’s missed, who’s banned Mr. Buffett so generously sent to the Rose Bowl Parade last year. So, you’re a very popular guy in my town. Good morning, Mr. Buffett. Mr. Munger. Mr. Buffett, I w…