120 likes | 141 Views
Booleans and Selection Statements. FOP Unit 2, Day 3 Dr. Sarah Diesburg. Some Terms. Boolean – a special type that is either True or False Boolean expression – something Python evaluates to True or False: num <= 5 name == “Sarah” temp > 30 and weather == “sunny”. Python if Statement.
E N D
Booleans and Selection Statements FOP Unit 2, Day 3 Dr. Sarah Diesburg
Some Terms • Boolean – a special type that is either True or False • Boolean expression – something Python evaluates to True or False: • num <= 5 • name == “Sarah” • temp > 30 and weather == “sunny”
Python if Statement if Boolean expression: suite • Evaluate the expression to a Boolean value (True or False) • if True, execute all statements in the suite
Warning About Indentation • Elements of the “suite” must all be indented the same number of spaces/tabs • Python only recognizes suites when they are indented the same “distance” • You must be careful to get the indentation right to get suites right.
Using else if Boolean expression: suite1 else: suite2 The process is: • evaluate the Boolean • if True, run suite1 • if False, run suite2
Using elif if boolean expression1: suite1 elif boolean expression2: suite2 #(as many elif’s as you want) else: suiteLast
if, elif, else, the Process • Evaluate boolean expressions until: • The boolean expression returns True • None of the boolean expressions return True • If a boolean returns True, run the corresponding suite. Skip the rest of the if • If no boolean returns True, run the else suite, the default suite
Compound Expressions • Logical operators can evaluate two or more Boolean statements together • and • or • not
Using “and” if leftPen==“purple” and rightPen==“gold”: print(“I am holding both UNI colors.”) • We only execute the print statement if both Boolean expressions are True. • If they are not both True, we just skip
Using “or” if leftPen==“purple” or rightPen==“gold”: print(“I am holding at least one of the UNI colors.”) • We execute the print statement if at least one of the Boolean expressions are True.
Using “not” If not (age >= 21): print(“You can’t buy alcohol.”) • The not word flips the Boolean expression to its opposite • In this example, print will execute if age is not >= 21
Using “not” • You can use “not” to flip compound statements to their opposite if not (leftPen==“purple” and rightPen==“gold”): print(“I am definitely not holding both UNI colors.”)