Review - Conditionals

Boolean Values

What are the two possible Boolean values? How are they represented in Python?

A Quick Aside on bool Types

If bool is the name of the type, what do you expect the name of the function to convert to this type is?

>>> bool(0)
False
>>> bool("a string")
True
>>>

== And =

What's the difference between == and =?

The Equality Operator

Some details about how == works:

A few examples:

If Statements

How do we construct an if statement? Why does indentation matter?

print("before my if statement")
if foo == bar:
	print "they are equal"
print("after my if statement")

On Indentation

Um, BTW - how do we know when a block of code ends?

This or That

What construct (keyword) would you used to execute a block of code only if the condition in the original if-statement is not met? What is the syntax for using it?

#  use the keyword, else
if some_boolean_expression:
	print('yes, that\'s true!')
else:
	print('nope, totally false!')

Note that else will always have a corresponding if statement.

What's the Output? Part 1!

What's the output of this program?

flag = True
print('one')
if flag:
	print('two')
else:
	print('three')
print('four')
one
two
four

What's the Output? Part 2!

What is the output of this program if the user enters 'Yes', 'yes', and 'whatevs'?

answer = input("you have 12 doughnuts, would you like another dozen?\n>")
if answer == 'yes':
	print('you have 24 doughnuts')
else:
	print('you have 12 doughnuts')
you have 12 doughnuts, would you like another dozen?
>Yes
you have 12 doughnuts

you have 12 doughnuts, would you like another dozen?
>yes
you have 24 doughnuts

you have 12 doughnuts, would you like another dozen?
>whatevs
you have 12 doughnuts

What's the Output? Part 3!

What happens if the user enters 16?

answer = input('what is 2 to the 4th power?\n>')
if answer == 2 ** 4:
	print('yup, you got it!')
else:
	print('close, but no cigar!')
close, but no cigar!

…will this ever print 'yup, you got it!'? why?

no, because it is always comparing a string to an int

Number Guessing Game

Create a game that

please enter a number
>2
the secret number was 5, not 2
please enter a number
>5
yeah, you got it!

A Possible Solution

secret = 5
n = int(input('please enter a number\n>'))
if n == secret:
	print('yeah, you got it!')
else:
	print('the secret number was ' + str(secret) + ', not ' + str(n))

A Few Terms

if statement header line and body:

n = int(input("number plz\n>")

#  if statement header line
if n == 42:

	# if statement body
	print('that's the meaning of life!')
	print('!!!!')

One Last Pass

You can use the keyword pass to tell Python to do nothing. What do you think this prints out?

if True:
	pass

nothing!