3.1. If-Then Statements#

There will be times when we only want to do things only when certain conditions are met. In order to facilitate this within a programming language we need a way for the program to know the “truthiness” of a statement.

If statements are used for when you want your code to be able to make a choice based on some condition. This will allow your code to be more flexible to create a wider variety of outcomes from running that same code.

The manner in which these statements work is by testing a truth value of a statment. If the statement is true, then the code within the if statement will be executed.

Logical Operators#

In order test values we need a set of operators that can help the computer determine the “truthiness”. Here are the list of the most common logical operators used in Python.

symbol

meaning

<

less than

<=

less than or equal

>

greater than

>=

greater than or equal

==

equal to

!=

not equal to

and

or

not

|

bitwise or

&

bitwise and

The non-bitwise and, or, and not evaluate the truthiness of the statements it is comparing, whereas the & and | operators work on the byte representations of any value to assess its truthiness. More likely than not, it will be best to use the non-bitwise versions.

NOTE: zero or empty objects are False, all other values and non-empty objects are True)

Let’s test out the operators…

# Examine truthiness of statement
print(5 < 10)
True

If, Else If, Else Statements#

At a minimum you must include a single if call, but can then include any number of elif statements to check other possibilities, and then a single concluding else statement can be used as a catch-all for the if statement (with no need to have any elifs to have an else). Here is a full example of using if, elif, and else in a single if statement. Notice that at the end of each line contain a part of the if construct there is a colon (:), that is the important character for the Python interpreter to know it has reached the end of the logical statment and it should be evaluted to determine its truithiness. Also note that the else statement does not contain any logical condition as it only gets executed if each test before it results in a False designation.

a = 5
b = 10

if a < b:
    print(a)
elif a == b:
    print('a and b are equal')
else:
    print(b)

Output:

5

NOTE: Another key element of Python is that is is an indented language, so everything within the if statment and any elif or else statments must be indented the same amount. The standard indent is four spaces long.

if statment construct - stand alone#

Here is the construct of a simple if statment where you are looking to test a single conditional element (e.g., 5 < 10) to then choose to take a specific action (whatever is in the code block indented with the if statement) if it is True.

if condition:
    [code block]
# If-Then Statement Example 1
from datetime import datetime, timedelta

current_date = datetime.utcnow()
print(f'Original Time: {current_date}')

minute = current_date.minute

if minute < 15:
    current_date -= timedelta(hours=1)
print(f'Time after If-Statement: {current_date}')
Original Time: 2024-08-30 15:22:16.256179
Time after If-Statement: 2024-08-30 15:22:16.256179

if-else construct#

If you want to test one conditional, but if it is False, always do something else, then the if-else construct is for you! Note that in the else there is no conditional statement as it is a catch-all and will always be executed if the initial conditional is False.

if condition:
    [code block]
else:
    [default code block]

if-elif-else construct#

The full complement of an if statement can contain one if, any number of elifs, and an else statment. Again, once a True condition is found it will run the code block associated with that condition and then move on in the program after the if statment.

if condition1:
    [code block one]
elif condition2:
    [code block two]
elif condition3:
    [code block three]
else:
    [default code block]
# if-elif-else statement

grade = 75

if grade >= 85:
    print('You got a great score')
elif grade >=70:
    print('You got a good score')
else:
    print("Let's work together to improve your score on a future assignment.")
You got a good score