Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand...
Transcript of Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand...
Control Flow: Branchingbooleans and selection statements
CS 112 @ GMU
• booleans• selection statements:
– if– if-else– if-elif(s)– if-elif(s)-else
• flow charts
2
Topics
Booleans
Booleans - examples
Booleans are either True or False. We create them in many ways.• 3<4 → True• 17%2==0 → False• 2<5 or 10>20 → True• not True → False• "hello"=="HELLO" → False
Booleans – definition
• bool is another Python type.• It has exactly two values: True, False.• many operators and functions will result in a
boolean value• they can be used to make decisions: if an
expression results in True, do one thing (run one block of code); if False, do another thing (go to a different place in code)
Booleans – operators
three main operations that we do with booleans: and, or, not
• expr1 and expr2: are both exprs True?
• expr1 or expr2: is at least one expr True?• not expr: switch between True/False
Booleans – truth tables
• We can exhaustively describe all combinations of inputs for and, or, and not.
x y x and y
False False False
False True False
True False False
True True True
x y x or y
False False False
False True True
True False True
True True True
x not x
False True
True False
Booleans – more operators
• numbers and other types of values can be used to generate booleans with various operators:
operator meaning arguments
a < b less than numbers
a <= b less than or equal numbers
a > b greater than numbers
a >= b greater than or equal numbers
a == b equality check anything!
a != b inequality check anything!
Poll – 2.1
Booean expressions
Chained Comparisons
• Python is a bit unique in allowing chained comparisons:
• x<y<=z is equivalent to (x<y) and (y<=z)• short circuiting: from left to right, if any relation
in the chain is False, we know the overall answer is False, so no further relations are checked.– (above: if x<y is False, don't check y<=z)
Impostors!
• Python will happily and silently (and unfortunately) let us use non-booleans where boolean values are expected
→ zero numbers are treated as False→ non-zero numbers are all treated as True→ other non-booleans have boolean interpretations too
Suggestion: try to only use actual boolean expressions where booleans are needed!
TRAP
Note the difference:
x = 5 assignment statementx == 5 boolean expression
Python can tell if you put an assignment where an expression should go, but will not complain when an expression is where an assignment should go.
more boolean expressions
x<y not (3<y)(x<y) and b not (not b)x<y<b "test"=="test"3>y "test"=="Test"3>y and x<=y not b == y<x3>y or x<=y x+x == yFalse == False False == (not b)
Assume that x=2, y=4, b=True. Simplify each expression.
more boolean expressions
x<y not (3<y)(x<y) and b not (not b)x<y<b "test"=="test"3>y "test"=="Test"3>y and x<=y not b == y<x3>y or x<=y x+x == yFalse == False False == (not b)
True FalseTrue True(False!) TrueFalse FalseFalse TrueTrue TrueTrue True
Assume that x=2, y=4, b=True. Simplify each expression.
Branching
http://www.soberinanightclub.com/2010/03/am-i-horse.html
selection statements
• we can select different blocks of code to run based on a boolean expression's value:
val=int(input("temperature: "))
if val > 80:print("hot today.")
elif val >= 65:print("I can manage.")
else:print("where's my jacket?")
dist = int(input("dist?"))if dist >= 26.2:
print("marathon, wow!")print("good run.")
if payment>cost:change = payment – costprint("change: "+str(change))
else:print("not enough money!")
if-statement
• an if-statement guards a block of code with a booleanexpression.– if the expression is True, then
run the block– if the expression is False, then
skip the block• decision: do I perform or skip
this indented block of statements?
if expr:stmts
Selection statement – example 1
val = int(input("number to check: "))if val==10:
print("ten is great!")print("thanks!")
• we only print "ten is great!" when val currently stores 10; other times, we skip that indented code.
• "thanks!" always prints, because it follows theif-statement (it isn't indented)
if-else statement
an if-else statement guards two blocks of code with a boolean expression.• if expr is True, then run only
the first block• if expr is False, then run only
the second blockdecision: which of two blocksof code do I run?
if expr:stmts1
else:stmts2
Selection statement – example 2
val = int(input("number to check: "))if val==10:
print("A: ten is great!")else:
print("B: I dislike that number.")print("thanks!")
• we always print either message A or B, but not both.• "thanks!" always prints, because it follows the
selection statement
if-elif statement
an if-elif statement guards two or more blocks of code with multiple booleanexpressions.• check each boolean expr in order until you
find the first True one.• Only run corresponding block of code• may have a single else block at the end
Decision: which of many things to run?→ no else block: might run none of them
if expr1:stmts1
elif expr2:stmts2
elif expr3:stmts3
…else:
stmtsN
Selection statement – example 3val = int(input("number to check: "))if val<10:
print("A: small number")elif val==10:
print("B: perfect size!")else:
print("C: too big.")print("thanks!")
• we always print exactly one of messages A or B or C, but not multiple of them, and not zero of them.
• we could omit the else branch, and for big inputs only "thanks!" would print.
• "thanks!" always prints, because it follows the selection stmt
Selection statement – example 4val = int(input("number to check: "))if val<10:
print("A: small number")elif val==10:
print("B: perfect size!")elif val<100:
print("C: a bit too big.")print("thanks!")
• we print at most one of messages A or B or C• "thanks!" always prints, because it follows the selection stmt
note: else blocks
• the else block is an optional addition to a selection statement, whether it has zero, one, or many elif branches.
• it always defines the "default" behavior: when none of the boolean expressions were True, this else block is what should be run.
Poll – 2.2
Selection Statements
flow charts
• branches in flow charts have multiple paths that split and rejoin
• they can become selection statements: each separate path is an if/elif/else block
• one separate path may itself contain further subdivisions/splits that rejoin to each other (nested selection statements)
selections, flow charts - example
guess = int(input("your guess: "))secret = 42
if guess > secret:print("too big.")
elif guess < secret:print("too small.")
else:print ("correct!")
print ("thanks for guessing!")
get number guess from user
too high?
print "too big"
print"too small"
too low?
print"correct!"
thanks for guessing!
True
True False
False
practice: flow chart to code #1
if c :s1
s2
c
s1
s2
FalseTrue
practice: flow chart to code #2
if c1 :s1
elif c2:s2
s3
c1
s1
s2
FalseTrue
c2
s3
True False
practice: flow chart to code #3
if c1 :s1
elif c2:s2
else:s3
s4
c1
s1
s2
FalseTrue
c2
s4
True False
s3
practice: flow chart to code #4
s0if c1:
s1if c2:
s2if c3:
s3s4
c1
c2
c3
s1
s2
s3
s4
s0 • what possible paths are there through this code?
• would this code behave differently if we used elif's for c2 and c3?
True
True
True
False
False
False
practice: flow chart to code #5if c1:
s1if c2:
s2s3
else:s4if c3:
s5else:
s6if c4:
s7s8
s9
c2 c3
s1
s2
s3
s4c1
s5 s6
c4
s7
s8
s9
False
False
False
False
True
True True
True
selection statements – recap
• if: choose whether to run a block of code or not, based upon a boolean expression
• if-else: choose which of two things to do• if-elif(s): choose one of many blocks of code, by finding first True
boolean expr. Might choose none of them (all were False)• if-elif(s)-else: choose exactly one of many blocks of code, by
finding first True boolean expr (or running else block when all were False)
• flow charts: there are direct mappings between flow chart shapes and code.
Poll – 2.3Selection Statements