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. →
a,b="foo","bar"
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
a,b="foo","bar"ifa!=b:# totally ok? yes!# but why?# perhaps when done more reasonably, readabilityprintaprintaprintbprintb
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…
"""
Do you want cake?
> yes
Here, have some cake.
Do you want cake?
> no
No cake for you.
Do you want cake?
> blearghhh
I do not understand.
"""
Consecutive Ifs
One way to do it is consecutive if statements… →
answer=input("Do you want cake?\n> ")ifanswer=='yes':print("Here, have some cake.")ifanswer=='no':print("No cake for you.")ifanswer!='yes'andanswer!='no':print("I do not understand.")
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? →
answer=input("Do you want cake?\n> ")ifanswer=='yes':print("Here, have some cake.")elifanswer=='no':print("No cake for you.")else:print("I do not understand.")
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