Decisions in Python If / else A two-way branch • Many times you need to test for a condition and do actions BOTH if it is True or if it is False • This is where the if/else statement becomes useful Syntax of if/else • First part is an if statement with condition and colon • Then the statements which will be done if the condition is True, indented as usual • Then the keyword else and a colon, lined up under the if statement • Then the statements which will be done if the condition is False, indented as the other one is Example • The two branches cannot be empty, they can be as small as one statement but they have to have something in each • if x > 0: print(“ok”) else: print(“sorry”) Semantics of if/else • The condition at the if line is always executed, as with a plain if statement • If the condition is True, the statements indented under the if line are executed • If the condition is False, the statements indented under the else line are executed • Exactly one of the two branches will be executed on any particular run of the program Alignment of else with if • You do not have to have an else with every if statement. • BUT if you have an else: you must have an if to go with it. You cannot start a statement with else! • The indentation determines which if that an else goes with Do these do the same thing? if x > y: if y > 25: print(“a”) else: print(“b”) if x > y: if y > 25: print(“a”) else: print(“b”) “Factoring out” • If a statement appears in both branches, at the same point in execution, then ‘factor it out’ and put it just one time either before or after the if/else statement • if y + z > x: print(“ok”) t=1 else: print(“ok”) t=2 • The print(“ok”) statement can be done before the if statement starts Shortcut for Booleans • If you are writing an if statement to test a Boolean variable, you can write the condition as a ‘short cut’ • if bool_var == True: can be written as just if bool_var: • Remember that the if statement needs a Boolean value at that point and the bool_var is assumed to contain one, so comparing it to True is not necessary • If you needed the opposite test, you can write “if not bool_var:”