Control Flow: Branching booleans and selection statements CS 112 @ GMU
Topics booleans selection statements: if if-else if-elif(s) if-elif(s)-else flow charts 2
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 x y x or y x not x False False False False False False False True False True False False True True True False True False False True False True True True True True True True
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 (boolean expressions) 1.Given this code, answer each with the result of the expression. x=2 y=4 a) (x<y) and b b=true b) (not b)==false c) 3>y and x<=y d) "test" == "Test" 2. Only knowing that x, y, and z are integers, what is the result of the following expression? (not (x<y and y<z)) == (x>=y or y>=z))
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 x == 5 assignment statement 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 Assume that x=2, y=4, b=true. Simplify each expression. 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<x 3>y or x<=y x+x == y False == False False == (not b)
more boolean expressions Assume that x=2, y=4, b=true. Simplify each expression. True x<y False not (3<y) True (x<y) and b True not (not b) (False!) x<y<b True "test"=="test" False 3>y False "test"=="test" False 3>y and x<=y True not b == y<x True 3>y or x<=y True x+x == y True False == False True False == (not b)
Branching
selection statements we can select different blocks of code to run based on a boolean expression's value: dist = int(input("dist?")) if dist >= 26.2: print("marathon, wow!") print("good run.") if payment>cost: change = payment cost print("change: "+str(change)) else: print("not enough money!") val=int(input("temperature: ")) if val > 80: print("hot today.") elif val >= 65: print("i can manage.") else: print("where's my jacket?")
if-statement an if-statement guards a block of code with a boolean expression. 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
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 block decision: which of two blocks of code do I run? if expr: stmts1 else: stmts2
if-elif statement an if-elif statement guards two or more blocks of code with multiple boolean expressions. 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 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 Ymes, we skip that indented code. "thanks!" always prints, because it follows the if-statement (it isn't indented)
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 selecyon statement
Selection statement example 3 val = 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 mulyple 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 selecyon stmt
Selection statement example 4 val = 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 selecyon 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) 1. What is the final value of x? x = 5 if x>0: x += 3 if x>6: x += 10 if x>100: x = 123 2. What is the final value of x? x = 15 if x%7>1: x = x + 100 else: x = x + 6 if x%3==0: x = x * 2 3. What is the final value of x? x = 20 if x > 25: x += 100 if x > 15: x += 200 if x > 5: x += 400
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 True get number guess from user too high? False if guess > secret: print("too big.") elif guess < secret: print("too small.") else: print ("correct!") print "too big" True print "too small" too low? False print "correct!" print ("thanks for guessing!") thanks for guessing!
practice: flow chart to code #1 True c False if c : s1 s2 s1 s2
practice: flow chart to code #2 True c1 False if c1 : s1 True s2 c2 False s1 elif c2: s2 s3 s3
practice: flow chart to code #3 True c1 False if c1 : s1 True c2 False s1 elif c2: s2 s3 s2 else: s4 s4 s3
practice: flow chart to code #4 s1 s2 s3 True True True s0 c1 c2 c3 False False False s0 if c1: s1 if c2: s2 if c3: s3 s4 what possible paths are there through this code? would this code behave differently if we used elif's for c2 and c3? s4
practice: flow chart to code #5 s1 True c1 False s4 if c1: s1 if c2: True c2 False True c3 False s3 s2 s2 s5 s6 else: s4 s3 True s7 c4 False if c3: else: s5 s6 s8 if c4: s7 s9 s9 s8
Poll 2.3 1. What is the final value of x? x = 10 if x==20: x = 100 elif x>5: if x<50: x += 1 else: x += 4 elif x>=0: x = 3 if x%2==1: x += 1000 (selection statements) 2. Match each usage to a description. #1 if else #2 if elif #3 if elif elif else #4 if if if #5 if a) three separate choices to do or not do separate blocks of code b) select whether to do something or not c) select one or another action or alternatively do nothing d) select one of many blocks of code e) select one of two things to do
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.