If Statements / Conditionals
Back to the Lecture at Hand?
Anatomy of an If Statement (Again)
Write an if statement testing if a and b are not equal. If they're not equal, print the value of a and b twice. →
- begin with keyword if
- condition
- colon - ends the condition / marks that a block of code is about to come up
- if + condition + colon usually is considered the if-statement header
- body of if statement ends when indentation goes back one level
- blank lines don't count as ending a block of code!
Let's See That Again
Oh Yeah, Else What?
We can use else to execute code if the original condition was not met
- go back one level of indentation to mark that the previous code block has ended
- keyword else
- body - indented, body ends when indentation goes back one level
- not required, obvs
What About Multiple Chained Conditions?
What if else is not fine-grained enough? For example, how about a program that asks for cake and handles a yes, no, or anything other than…
Consecutive Ifs
One way to do it is consecutive if statements… →
Else If (elif)
We can use elif to chain a series of conditions, where only one path of code will be executed
- if statement like usual
- go back one level of indentation to mark that the previous code block has ended
- keyword elif
- condition
- colon
- body - indented, body ends when indentation goes back one level
- not required obv
- even if more than one true, only the first true executes!
- can add an else at the end
elif Example
How would we redo the cake exercise with elif? →
Nesting If Statements
- it behaves as you'd expect
- remember to get indentation right
- if there are multiple elif's or else's, you can use indentation to see which initial if statement they belong to
- this works for any combination of if, elif and else
- note that sometimes nested if statements are equivalent to and
- best to simplify - that is, less nesting, better