Conditional statements¶
Sources¶
This lesson is based on the Software Carpentry group’s lessons on Programming with Python.
Basics of conditional statements¶
Conditional statements can change the code behavior based on meeting certain conditions.
Let’s take a simple example.
>>> num = 37 >>> if num > 100: ... print('greater') ... else: ... print('not greater') ... not greater
What did we do here? First, we used the
if
andelse
statements to determine what parts of the code to execute. Note that both lines containingif
orelse
end with a:
and the text beneath is indented. What do these tests do? Theif
test checks to see whether the variable value fornum
is greater than 100. If so, ‘greater’ would be written to the screen. Since 37 is smaller than 100, the code beneath theelse
is executed. Theelse
statement code will run whenever theif
test is false.The combination of
if
andelse
is very common, but both are not strictly required.>>> num = 53 >>> if num > 100: ... print('53 is greater than 100') ... >>>
Note that here we use only the
if
statement, and because 53 is not greater than 100, nothing is printed to the screen.We can also have a second test for an
if
statment by using theelif
(else-if) statement.>>> num = -3 >>> if num > 0: ... print(num, 'is positive') ... elif num == 0: ... print(num, 'is zero') ... else: ... print(num, 'is negative') ... -3 is negative
Makes sense, right? Note here that we use the
==
to test if a value is equal to another. The complete list of these comparison operators is given in the table below.Operator Meaning <
Less than <=
Less than or equal to ==
Equal to >=
Greater than or equal to >
Greater than !=
Not equal to We can also use
and
andor
to have multiple conditions.>>> if (1 > 0) and (-1 > 0): ... print('Both parts are true') ... else: ... print('One part is not true') ... One part is not true >>> if (1 < 0) or (-1 < 0): ... print('At least one test is true') ... At least one test is true
This can be quite handy.