Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand...

35
Control Flow: Branching booleans and selection statements CS 112 @ GMU

Transcript of Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand...

Page 1: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Control Flow: Branchingbooleans and selection statements

CS 112 @ GMU

Page 2: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

• booleans• selection statements:

– if– if-else– if-elif(s)– if-elif(s)-else

• flow charts

2

Topics

Page 3: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Booleans

Page 4: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 5: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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)

Page 6: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 7: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 8: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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!

Page 9: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Poll – 2.1

Booean expressions

Page 10: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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)

Page 11: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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!

Page 12: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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.

Page 13: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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.

Page 14: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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.

Page 15: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Branching

Page 16: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

http://www.soberinanightclub.com/2010/03/am-i-horse.html

Page 17: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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!")

Page 18: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 19: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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)

Page 20: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 21: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 22: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 23: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 24: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 25: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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.

Page 26: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Poll – 2.2

Selection Statements

Page 27: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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)

Page 28: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 29: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

practice: flow chart to code #1

if c :s1

s2

c

s1

s2

FalseTrue

Page 30: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

practice: flow chart to code #2

if c1 :s1

elif c2:s2

s3

c1

s1

s2

FalseTrue

c2

s3

True False

Page 31: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

practice: flow chart to code #3

if c1 :s1

elif c2:s2

else:s3

s4

c1

s1

s2

FalseTrue

c2

s4

True False

s3

Page 32: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 33: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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

Page 34: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

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.

Page 35: Control Flow: Branchingmarks/112/slides/2.branching.pdf · Control Flow: Branching booleansand selection statements ... x = 5 assignment statement x == 5 booleanexpression Python

Poll – 2.3Selection Statements