Topics
Simple if/ else
Deciding on different path of execution. In python, decision making is done with if, and else statements.
Example of a simple if/else statement:
mark = 51 if mark >= 50: # executed if mark >= 50 print "You passed the test!" else: # executed if mark < 50 print "You failed the test!"
Chained Conditions
In cases where there are more than two possible paths of execution, you can use the if/elif/else block as shown below:
mark = 51 if mark >= 70: # executed if mark >= 70 print "You scored an 'A'!" elif mark >= 60: # executed if mark >= 60 print "You scored a 'B'!" elif mark >= 50: # executed if mark >= 50 print "You scored a 'C'!" else: # executed if mark < 50 print "You failed the test!"
Logical Operators: and & or
Use and operator to make complex decisions involving two (or more) conditions. The result is True only if both conditions evaluate to True. See Example below:
>>> True and True True >>> False and True False >>> True and False False >>> False and False False
The or operator works in the same way. The result is True if either one of the conditions evaluates to True.
>>> True or True True >>> True or False True >>> False or True True >>> False or False False
Logical Operators (Examples)
Applying the same principle, a combination of and and or operators can be used to make complex decisions involving 3 or more conditions.
>>> True or True and False False >>> False and True or True True >>> True or False and True True
Examples of using and and or operators for decision making:
def get_results(test1, test2): if test1 >= 50 and test2 >= 50: print "Passed both tests!" elif test1 >= 50 or test2>= 50: print "Passed at least one test!" else: print "Failed both tests!"
Calling the get_result() function:
>>> get_result(40, 60) Passed at least one test! >>> get_result(51, 52) Passed both tests! >>> get_result(23, 43) Fail both tests!
The Nested if/else Construct
It is possible to nest if/else statement within other if/else statement, creating nested structure. This is usually used to test two or more different conditions. See example below:
if gender = 'M': if age > 12: discount = 5 else: discount = 10 else: if age > 12: discount = 10 else: discount = 15
Code Snippets
This section will contain some code snippets to show some practical use of the topic that you have learnt.
# Calculating BMI # Underweight = < 18.5 # Normal weight = 18.5 - 24.9 # Overweight = 25 - 29.9 # Obesity = BMI of 30 or greater # ------------------------------ weight = 65.0 height = 1.7 bmi = weight / (height * height) if bmi < 18.5: print "Underweight" elif bmi < 25: print "Normal weight" elif bmi < 30: print "Overweight" else: print "Obesity"