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.

a, b = "foo", "bar"

Let's See That Again

a, b = "foo", "bar"
if a != b:
	# totally ok?  yes!
	# but why?
	# perhaps when done more reasonably, readability
	print a
	print a


	print b

	print b

Oh Yeah, Else What?

We can use else to execute code if the original condition was not met

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> ")
if answer == 'yes':
        print("Here, have some cake.")
if answer == 'no':
        print("No cake for you.")
if answer != 'yes' and answer != '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

elif Example

How would we redo the cake exercise with elif?

answer = input("Do you want cake?\n> ")
if answer == 'yes':
        print("Here, have some cake.")
elif answer == 'no':
        print("No cake for you.")
else:
        print("I do not understand.")

Nesting If Statements