# -*- coding: utf-8 -*- # Rodrigo Muñoz # 6.S189 Lecture 2 # Conditional Operators, Branching # ===================== # Conditional Operators # ===================== # So far we've learnt about +-*/ etc... # These take in a number and return another number # Remeber: Boolean types. True or False. (Note distinct lack of quotes. These are not strings!) # New operators: >, >=, <, <=, ==, != # Examples, greater than, less than: print "Conditional Operators:" print "9 > 5:", 9 > 5 print "15 < 9:", 15 < 9 # == is a logical "equals" # returns True if both items are equal, False otherwise # VERY IMPORTANT: "=" is assignment operator. "==" is the comparison operator. print "7 == 7:", 7 == 7 print "7.0 == 7:", 7.0 == 7 print '"apple" == "orange":', "apple" == "orange" print "True == False:", True == False # analogously, != is a logical "not equal to" print "type(0.5) != type(True):", type(0.5) != type(True) # As with other stuff, we can store results to variables bool1 = 3 > 2 print "bool1 = 3 > 2" print "bool1 =", bool1 # There are some other operators we can use for boolean logic # These are "and", "or", and "not" # a and b is true if a is true and b is true # a or b is true if either a or b are true # not a is true if a is false print "True and True:", True and True print "True and True and False:", True and True and False print "True or False:", True or False print "False or False or True:", False or False or True print "not False:", not False # ============================= # Branching (aka if statements) # ============================= # Branching allow us to run certain instructions if a particular condition is met if "apples" != "oranges": print "All systems in order!" # Note: If can be all by itself, if the else clause would be "do nothing" myGrade = "Failing" if myGrade == "Passing": print "Yay!" else: print "D'oh!" yourGrade = raw_input("What's your grade? ") if yourGrade == "P": print ":D" elif yourGrade == "D": print ":|" elif yourGrade == "F": print ":(" else: print "Wait, what?" # Note that the order of evaluation matters! # If at all possible, make it such that only one conditional can be true at once! # In the example below, we'd want the code to output "It's freezing.", but since the # conditionals are evaluated in order, we are actually outputting "It's not that bad." temperature = 30 if temperature < 70: print "It's not that bad." elif temperature < 50: print "Okay, it's a bit chilly." elif temperature <= 32: print "It's freezing." # Also note, it's perfectly fine for a conditional statement not to have an else statement.