Conditional statements are tests to return whether a given comparison between two variables is True
or False
. They are used in combination with if
-statements to control the flow of a program. For example, we may want to check if the inputs to a particular function or program is within some valid range, or non-negative. In the event that it is a valid input, we proceed with the calculations. In the event that it is an invalid input, we terminate the program and prompt the user to input a parameter that is valid.
Conditional operators
The conditional operators in Python consist of the following:
==
for testing if two data types are equal to each other!=
for testing if two data types are not equal to each other>
for testing if one data type is greater than another<
for testing if one data type is less than another>=
for testing if one data type is greater than or equal to another<=
for testing if one data type is less than or equal to another
A few code examples with obvious outputs are shown below
print(5 == 5)
print(5 != 6)
print(10 > 9)
print(9 < 10)
print(10 >= 10)
print(9 <= 10)
You can negate any operation above by placing the not
keyword in front of it, e.g.
not 5 == 5
You can also test if one element is a subset of another, e.g.
'Hello' in 'Hello, World!'
(9 <= 9) and (9 < 10)
These follow the following boolean logic
- True
and
True = True - True
and
False = False - False
and
False = False - True
or
True = True - True
or
False = True - False
or
False = False
As many and
and or
statements can be combined as desired:
It's a good idea to use parenthesis when combining multiple and
/or
operations to ensure clarity in the order of operations.
(True and False) or True
if
, elif
, else
statements
We control the flow of a program with if
-statements. if
-statements use conditionals as a test and then execute code in the body of the if
-statement when the test is True
. Below we define a function that takes a number x
as an argument and prints 'x is positive'
if (and only if) the input value for x
is greater than 0.
Notice the colon :
after the conditional test, this starts the body of the if
-statement. The body is identified by a consistent indentation underneath. Typically this indentation is 4 spaces, but any consisent indentation amount for the lines in the body is acceptable.
def test_if_x_is_positive(x):
if x > 0:
print('x is positive')
Running the function with a few inputs
test_if_x_is_positive(5)
test_if_x_is_positive(-5)
Notice the second function call does not return anything at all, this is because the conditional statement evaluated to False
and therefore the body of the if
-statement was never executed. We can add a else
clause to the elif
-statement (shorthand for else if that will execute given another conditional statement, perhaps checking to see if x
is negative.
def test_if_x_is_positive_or_negative(x):
if x > 0:
print('x is positive')
elif x < 0:
print('x is negative')
Running the function with a few inputs
test_if_x_is_positive_or_negative(5)
test_if_x_is_positive_or_negative(-5)
achieves the expected result. What about the case when x
is exactly 0?
test_if_x_is_positive_or_negative(0)
This case does not return any print statements because neither condition is met. We could write a thrid condition to test if x
is identically zero, or we could use an else
clause which can be thought of as the "otherwise" condition. The else
-statement will execute in the event that none of the if
or elif
conditions have been met. An else
-statement is not followed by a condition.
def test_if_x_is_positive_or_negative(x):
if x > 0:
print('x is positive')
elif x < 0:
print('x is negative')
else:
print('x is 0!')
test_if_x_is_positive_or_negative(0)
You can also nest if
-statements inside each other. There is no limit to how many times this can be done. An example is below. This function takes two arguments x
and truncate_value
. If x
is less thantruncate_value
it returns truncate_value
, otherwise is returns x
. It also allows truncate_value
to be defined as None
in which case it returns x
.
def truncate(x, truncate_value):
if truncate_value != None:
if x < truncate_value:
return truncate_value
else:
return x
else:
return x
truncate(5, 4)
truncate(-4, 0)
truncate(5, None)
While you can nest if
-statements to any level, the readability of the code begins to suffer the deeper you go. At some point, it's generally better for readability and debugging mistakes in the code to break out some of the logic into smaller functions. The example above is really too simple for this to be necassary, but an example is shown below to demonstrate the idea.
The double underscore __
in the function name __truncate
is simply a convention in Python to indicate that this function is never intended to be called directly by a user, but rather just a function that will be called in the body of other functions.
def __truncate(x, truncate_value):
if x < truncate_value:
return truncate_value
else:
return x
def truncate(x, truncate_value):
if truncate_value != None:
return __truncate(x, truncate_value)
else:
return x
truncate(-4, 0)
The first function __truncate
performs the truncation operation, but would error if truncate_value = None
. The second function checks to ensure that truncate_value != None
and if this is True
, then it calls the first function.
Further reading
Further reading on flow control can be found in the Python documentation.