184_notes:if

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
184_notes:if [2022/04/20 15:24] woodsna1184_notes:if [2022/05/07 01:21] (current) woodsna1
Line 1: Line 1:
 ====== Coding: "If Statements" ====== ====== Coding: "If Statements" ======
 +==== Lecture Video ====
 +
 +{{youtube>JSWKkB14HDI?large}} 
 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: 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:
 <code>  <code> 
Line 7: Line 10:
     quotient = numerator/denominator     quotient = numerator/denominator
 </code> </code>
-Everything that follows the word "if" is called the conditional. The code within an if statement 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".+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".
  
 ===== Else Clauses ===== ===== Else Clauses =====
Line 18: Line 21:
     quotient = 999999     quotient = 999999
 </code> </code>
-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.+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.
  
 ===== Nesting If Statements ===== ===== Nesting If Statements =====
 +==== Lecture Video ====
  
 +{{youtube>jUm8bSpLAmQ?large}} 
 Similarly to loops, we can use nested if statements: Similarly to loops, we can use nested if statements:
 <code> <code>
  • 184_notes/if.1650468257.txt.gz
  • Last modified: 2022/04/20 15:24
  • by woodsna1