Conditionals¶
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:
print "You passed the test!" # executed if mark >= 50
else:
print "You failed the test!" # executed if mark < 50
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:
print "You scored an 'A'!" # executed if mark >= 70
elif mark >= 60:
print "You scored a 'B'!" # executed if mark >= 60
elif mark >= 50:
print "You scored a 'C'!" # executed if mark >= 50
else:
print "You failed the test!" # executed if mark < 50
Logical Operators: and 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
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
See also
Ready for some practice? Test your understanding at PySchools: Conditionals.