184_notes:if

Coding: "If Statements"

Sometimes, we only want the computer to execute code in specific cases. For instance, only divide if the denominator is nonzero. How can the computer decide if the denominator is nonzero? One way is by using an if statement:

 
numerator = 1
denominator = 2
if denominator != 0:
    quotient = numerator/denominator

Everything that follows the word “if” is called the conditional. The code within an if statement (the indented code) will only execute if the conditional evaluates to True. In this case, we only compute the quotient for a nonzero denominator. You can read if statements out loud to understand what they're doing. In the above example, the if statement could be read as “if the denominator is not equal to 0, divide”.

We often want the computer to do something else if the conditional evaluates to False. We can accomplish this with an “else” clause:

if denominator != 0:
    quotient = numerator/denominator
else:
    quotient = 999999

In this code, the quotient will be set to some high number when the denominator is 0, instead of trying to calculate the true quotient. Code contained in else clauses only executes when the if statement's conditional evaluates to False. If the conditional is true, the else statement is skipped.

Similarly to loops, we can use nested if statements:

if numerator > 0:
    if denominator != 0:
        quotient = numerator / denominator

In this case, the quotient will only be calculated if the numerator is greater than zero and the denominator is nonzero. An alternative but equivalent way to write nested if statements is using “and” in the conditional:

if numerator > 0 and denominator != 0:
    quotient = numerator / denominator

These two code segments do exactly the same thing, but the second is usually easier to look at and understand.

  • 184_notes/if.txt
  • Last modified: 2022/05/07 01:21
  • by woodsna1