```
WEEK03: booleans, logical operators, conditionals (if/else)
---------------------------------------------------------------
M: quiz 1 on Wednesday, branching: booleans, if/elif/else

LAB2: due Saturday

REVIEW OF forloopsWorksheet.py and splitphrase.py:

for i in range(10):
print i * "x"

<-- 0 x's
x            <-- 1 x
xx           <-- 2 x's
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx
xxxxxxxxx    <-- 9 x's

for ch in "hello":
print ch * 3

hhh
eee
lll
lll
ooo

for ch in range(len("hello")):
print ch * 3

0
3
6
9
12

*** WHAT IS ch in the above two loops?

\$ python splitphrase.py

phrase: this is really quite fun!
this is real
-------------------------
ly quite fun!

phrase = raw_input("phrase: ")
length = len(phrase)
half = length/2

print " "*half + phrase[0:half]
print length * "-"
print phrase[half:]

BRANCHING...how do we do this in a program???

\$ python speed.py
How fast were you going? 50
OK...off you go.

\$ python speed.py
How fast were you going? 75

SLOW DOWN!!!!!!!!!!!!!

** need some way to test something and decide if it's True
or False. And if it's True, do one thing; if it's False,
do something else. This is called a BRANCH, as execution

BOOLEANS...a new type

>>> x = True
>>> type(x)
<type 'bool'>
>>> y = true
Traceback (most recent call last):
File < stdin > line 1, in < module >
NameError: name 'true' is not defined
>>> z = False
>>> type(z)
<type 'bool'>
>>> print z
False
>>>

COMPARISON OPERATORS (be careful with ==)

>>> i=10
>>> j=15
>>> i < j
True
>>> i > j
False
>>> i == j
False
>>> i >= j
False
>>> i != j
True
>>>

CONDITIONAL STATEMENTS:

if < condition >:
do this
and this
else:
do that

--> condition is an expression that evaluates to True or False

--> can do if without an else

>>> if i < j:
...   print "i is less than j"
...
i is less than j

>>> if i == j:
...   print "i and j are equal"
... else:
...   print "i is not equal to j"
...
i is not equal to j
>>>

--> can have more than two branches:

if expression1:
#
# code block done if exp1 is True
#
elif expression2:
#
# code block done if exp2 is True (and exp1 False)
#
elif expression3:
#
# code block done if exp3 is True (and exp1,exp2 False)
#
else:
#
# code block done if none of above were True
#

--> here's an example with grades:

letter = "A+"
letter = "A"
letter = "A-"
letter = "B+"
...
...
letter = "D-"
else:
letter = "F"

YOUR TURN: can you write this program?

\$ python countLetter.py
string: this is really fun!
letter: s
Number of s's in that string: 2

\$ python countLetter.py
string: sally sells shells by the seashore
letter: s
Number of s's in that string: 7

```