The if statement
For making choices among several alternatives, Python, like most languages, provides the ‘if’ statement. The ‘if’ statement is a compound statement, so Python’s indentation rules apply. The general format of ‘if’ is as shown:
if some condition: # if 'some condition' is True do something elif another condition: # else if another condition is True do something else elif yet another condition: # else if yet another condition is True do something else again ... # as many more elif statements as you like else: # if none of the above conditions is True do some default action
The ‘conditions’ referred to must be objects that have a True or False value, but in Python, this can be almost anything. Numeric objects are False if they are zero and True otherwise; strings are False if they are empty and True otherwise, and so on.
The bool() function
To determine the boolean value of an object, use the bool() function. Try typing the following into a Python console:
bool(0) bool(1) bool('') bool('wibble') bool(0 + 0j) bool(0 + 1j) bool(0 * 42) bool(12 - 12) bool(12 + 12) bool(0.1 + 0.2 - 0.3)
The last example returns True (even though the result should be 0), which is a result of the infamous roundoff error present when using floats.
The usual comparison operators are available in Python:
not equal to
less than or equal to
greater than or equal to
Comparisons between numeric types work as you’d expect. Comparisons between strings use alphabetical order to determine the result of <, <=, >, >= operations. This uses the ASCII ordering of characters, so uppercase letters are all before lowercase letters. Thus ‘Zebra’ < ‘aardvark’ is True, while ‘zebra’ < ‘aardvark’ is False. If you want a case-insensitive comparison, use
str.upper() to convert strings to uppercase, or
str.lower() to convert to lowercase.
Although you can’t use <, <=, >, >= operations with mixed data types (for example, ‘wibble’ > 42 gives an error), you can use == and != to compare any two data types. Not surprisingly == is always False if the data types don’t match. For example 0 == ” is False, even though you’re comparing zero to an empty string.
Unlike in many other languages, comparisons can be chained in Python, so expressions such as
1 < 2 < 4 < 12 (True) and
1 < 2 > 4 < 12 (False) are valid. A chained expression is True only if all its components (evaluated from left to right) are True.
Although the comparison operators do much what you’d expect, the boolean operators ‘and’ and ‘or’ are not entirely intuitive.
If you use them to compare the results of two comparisons, you’d get what you’d expect. For example,
1 < 2 and 2 + 4 == 6 returns True. It’s important to note that the boolean operators have a lower precedence than the comparison operators, which in turn have a lower precedence than arithmetic operators. In the expression
1 < 2 and
2 + 4 == 6,
2 + 4 is done first, then the comparisons
1 < 2 and
2 + 4 == 6 (in that order, left to right) and finally ‘and’ is applied to the results.
The catch is that boolean operators can be applied to any objects, not just to the results of comparisons. Consider the ‘and’ operator applied to two objects. A boolean ‘and’ is True only if both its operands are true, so we might expect 42 and 19 to return simply True (try it!). In fact, it returns the value 19, rather than just True.
The algorithm Python uses when confronted with an ‘and’ of two objects is to start with the left hand object and test whether it’s True or False. If it’s True, it then just returns the right hand object, regardless of whether it is True or False. If the left hand object is False, however, it gets returned immediately and the right hand object is ignored. Since the only way the ‘and’ of two objects is True is if both operands are True, taking the
bool() of the result always gives the right answer, but you need to be aware that the actual result of ‘and’ is not necessarily a boolean value.
For the ‘or’ operator, both operands are always evaluated. If only one of the operands is True, that one is returned. If both are True, the right hand one is returned. If both operands are False, the right hand one is returned.
The important thing to remember is that, unless the operands of ‘and’ and ‘or’ are themselves boolean quantities (False or True), the value returned will be an actual object, and not just a boolean quantity.
The ‘not’ operator, however, just returns False or True, and never any other quantity.
You should experiment with various data types to see how they behave with the comparison and boolean operators. In particular, take note of any combinations of data types that give errors.
Use your favourite search engine to read about Python’s
datetime module. Using this module, write a program that does the following:
- Determine the current time and print a welcome message that depends on the hour of the day. Print ‘Good morning’ if the time is between midnight and noon, ‘Good afternoon’ if the time is between noon and 6 PM, and ‘Good evening’ if the time is between 6 PM and midnight.
- Determine the day of the week and print out a message ‘Part of the working week’ if the day is Monday through Friday, or ‘It’s the weekend!’ if the day is Saturday or Sunday.
- Construct a datetime object for 31 December of the current year, and calculate how many days there are between now and the end of the year.
from datetime import * current = datetime.now() hour = current.hour if 0 <= hour <= 11: print('Good morning.') elif 12 <= hour < 18: print('Good afternoon') else: print('Good evening') dayOfWeek = current.weekday() if dayOfWeek != 6 and dayOfWeek != 7: print('Part of the working week') else: print('It\'s the weekend!') endOfYear = datetime(current.year, 12, 31) daysTillEnd = endOfYear - current print('Days until the end of', current.year, '=', daysTillEnd.days)
Line 2 uses the
now() function to get the current date and time. Line 10 uses the
weekday() function to find the day of the week, with Monday = 0 and Sunday = 7. Line 15 constructs a new datetime object for 31 December of the current year. On line 16, note that subtraction is defined for datetime objects, so we can use this to obtain the number of days between two dates.