Decision making plays a key role in programming and Python provides several ways to do that.
The if
statement is used to check if a condition is fulfilled and then a task (or set of tasks) is executed. The following example shows how it is used to check if a number is even:
number = 2
if number % 2 == 0:
print("number is even.")
The operator %
is called modulus and gives the remainder of an integer division (see section 1). The conditional expression follows directly after the word if
and ends with a colon :
(just as in the syntax for loops, see section 3). The task(s) to be executed in case the condition is True
, need to be indented (again as in the syntax for loops). Note that if the condition is not True
, the task is simply not executed.
number = 3
if number % 2 == 0:
print("number is even.")
An else
statement can be combined with an if
statement. An else statement contains the block of code that is executed if the conditional expression in the if
statement resolves as False
.
number = 3
if number % 2 == 0:
print("number is even.")
else:
print("number is odd.")
Just as loops can be nested within loops, if
statements can be nested within if
statements.
Now that you know the concept of loops and decision making, by combining them you can do a range of different tasks!
While n < 10
, print whether each number is odd or even.
# Exercise 4.2.1
for n in range(1,11):
if n % 2 == 0:
print('%d is even' % n)
else:
print('%d is odd' % n)
While n < 10
, find the number of values that are even.
# Exercise 4.2.2
counter = 0
for n in range(1,11):
if n % 2 == 0:
counter += 1
print(f"Number of even values: {counter}")
If there is more than one condition you want to check, you can add elif
statements to check each condition. You can have as many elif
s between an if
and else
as you want.
for n in range(-2, 2):
if n < 0:
print(f'{n} is negative')
elif n > 0:
print(f'{n} is positive')
else:
print(f'{n} is zero')
It is worth noting that in an if
.. elif
.. else
block, the first statement that returns as True
is executed.
In this section, we have covered:
if
statement.if .. else
statment.if .. elif .. else
statement.