Use the if
statement to make decisions in your code that affect the execution flow of the program.
Let's first review the floor division operator (//
) with its close companion the modulus operator (%
).
The //
operator divides and rounds down to an integer value if both arguments are integers, else a float.
Look at the output below and notice how all fractional parts are lost. When one argument is a floating point, the final result after the integer division is also a float (lines 3-5).
print(3 // 2)
print(1 // 2)
print(1.0 // 2)
print(1 // 2.0)
print(1.0 // 2.0)
1 0 0.0 0.0 0.0
The true power of these operators is in solving some common tasks. Let's look at some examples.
If a movie is 105 minutes long and you want to know how many hours and minutes that is, then you can use both operators to find out.
movieDuration = 105
hours = movieDuration // 60
minutes = movieDuration % 60
print('Movie duration:', hours, 'hour and', minutes, 'minutes')
Movie duration: 1 hour and 45 minutes
The %
operator can also be used to extract any number of digits from the right, i.e. least significant digits. Let's look at one example.
If the year
is 2021
, and you need the two-digit version then you can use:
year % 100
year = 2021
print(year % 100)
21
Divisibility is another example of the use of the %
operator. Let's see an example of that:
Is a number num
odd or even? Dividing by 2
and looking at the remainder should give us an answer. If the remainder is 0
then it is even, 1
it is odd.
numOdd = 21
numEven = 20
print('21 % 2?', numOdd % 2, '(odd)')
print('20 % 2?', numEven % 2, '(even)')
21 % 2? 1 (odd) 20 % 2? 0 (even)
Our last example is a favorite of mine. If you have a range of numbers, e.g. 0-2
and would like to cycle through each one as in 0 1 2 0 1 2 ...
you can use the %
to do this.
Look at the output below.
num = 0
print(num % 3)
num += 1
print(num % 3)
num += 1
print(num % 3)
num += 1
print(num % 3)
0 1 2 0
The reverse cycle is also possible with a small adjustment. Take a look at the code below and notice how we add 3
to num
before dividing. The reason for this becomes apparent when num
is 0
.
0 - 1 = -1
negative number means problem
-1 + 3 = 2
add the length of the range (3)
2 % 3 = 2
last number in the range
num = 2
print( (num + 3) % 3)
num -= 1
print( (num + 3) % 3)
num -= 1
print( (num + 3) % 3)
num -= 1
print( (num + 3) % 3)
2 1 0 2
A boolean expression is a binary expression that evaluates to either True
or False
.
True
and False
are both of type bool
.
print( type(True), type(False) )
<class 'bool'> <class 'bool'>
To form a boolean expression use the relational operators:
==
: equal!=
: not equal<
: less than<=
: less than or equal>
: greater than>=
: greater than or equalCareful not to use =
instead of ==
for equality, since that would cause a hard to find error.
To combine multiple expressions, use one of the three logical operators and
, or
or not
.
The expected arguments to these operators are boolean expressions. Although permissible you might want to avoid using numbers. Basically, any non-zero value is True
while 0
is False
.
42 and True
: True
age and True
: True
Let's take a closer look at how to write conditional statements that alter the execution flow of a program.
if
¶The simplest form of the if
statement is a single branch. Execute the statement(s) inside the body if condition is true, skip otherwise.
if x > 0:
print('x is positive')
x = 1
if x > 0:
print('x is positive')
x is positive
If you are not ready to implement the body use pass
as a placeholder.
if x < 0:
pass # FIX: handle negatives
elif
¶Use elif
to explore alternative branches or possiblities. Use as many as you need.
x = 1
if x > 0:
print('x is positive')
elif x < 0:
print('x is negative')
elif x == 0:
print('x is zero')
x is positive
else
An optional else
can be used to match all remaining branches.
Note: only one brach is ever executed, even if several branches evaluate to true. In that case the first branch that evaluates to true will be executed, and the if statement will terminate at that point.
weekDay = 6 # Sun = 0, ... Sat = 6
if weekDay >= 1 and weekDay <= 5:
print('Keep working hard')
else:
print("It's the weekend, relax")
It's the weekend, relax
The if
statement is similar in structure to a function, with a header and a body.
It is allowable to have if
statements inside any of the branches to form a nested if structure, but you want to avoid that if possible as it is harder to read and debug.
Use the logical operators to help you unnest such if statements.
Often you have to write a condition such as:
1 <= workDay and workDay <= 5
Python offers a shortcut for this:
1 <= workDay <= 5
Notice how this format has a more mathematical notation.
weekDay = 6 # Sun = 0, ... Sat = 6
if 1 <= weekDay <= 5:
print('Keep working hard')
else:
print("It's the weekend, relax")
It's the weekend, relax
Conditional expressions are indispensible when it comes to the idea of recursion.
Recursion is a solving technique that leads to elegant solutions. The idea being that a function calls itself in order to derive or converge to a known or base case.
Let's take a look at a simple counting example. Here we want to count down from a starting count all the way down to 0
.
def countDown(count):
if count == 0:
# base case, stop recursing
print('Blast off!')
else:
print(count, end = ' ')
# recursive step, thus continue on
countDown(count - 1)
countDown(5)
5 4 3 2 1 Blast off!
Let's look at another example that prints a string a number of times.
def repeatMessage(msg, times):
if times == 0:
return
else:
print(msg)
repeatMessage(msg, times - 1)
repeatMessage('Pizza!', 2)
Pizza! Pizza!
In both examples notice how we reduce the problem to a smaller version of itself. In the countDown example we decrement count
until we reach 0
, the base case. Similarly with the repeatMessage example, we decrement times
.
So the idea is basically this:
countDown(5)
: don't know how to do that, so print 5 and
countDown(4)
: don't know how to do that, so print 4 and
...
countDown(0)
: done
With recursive solutions one has to be mindful that the base case is reached. The base case recall stops the further recursive calls and begins the return journey or backtrack stage, all the way to the caller.
If the base case is never reached, infinite recursion will occur and Python will throw an error.
def infiniteRecursion():
infiniteRecursion()
infiniteRecursion()
--------------------------------------------------------------------------- RecursionError Traceback (most recent call last) <ipython-input-15-6f659e1ccf03> in <module> 2 infiniteRecursion() 3 ----> 4 infiniteRecursion() <ipython-input-15-6f659e1ccf03> in infiniteRecursion() 1 def infiniteRecursion(): ----> 2 infiniteRecursion() 3 4 infiniteRecursion() ... last 1 frames repeated, from the frame below ... <ipython-input-15-6f659e1ccf03> in infiniteRecursion() 1 def infiniteRecursion(): ----> 2 infiniteRecursion() 3 4 infiniteRecursion() RecursionError: maximum recursion depth exceeded
If your program needs input from the user, then use the input()
function.
The function returns a string
value and accepts an optional prompt.
If you want to input numbers, then convert the returned value using the appropriate conversion functions, int()
or float()
.
When you run this cell you will be presented with an input box at the top of the screen. Enter a value and press Enter
or Return
.
When you run this code in VSC as a code file (.py), you will be able to type the number in the Integrated Terminal at the bottom of the screen.
x = int( input('Enter an integer value:') )
if x < 0:
print('Negative number entered.')
elif x > 0:
print('Positive number entered')
else:
print('0 was entered')
Create a separate Python source file (.py) in VSC to complete each exercise.
The time
module provides a function, also named time()
, that returns the current Greenwich Mean Time in 'the epoch', which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.
import time
time.time()
Write a program that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.
Fermat's Last Theorem says that there are no positive integers $a$, $b$, and $c$ such that
$a^n + b^n = c^n$
for any values of $n$ greater than $2$.
Write a function named checkFermat()
that takes four parameters - a
, b
, c
, and n
- and checks to see if Fermat's theorem holds.
If $n$ is greater than $2$ and
$a^n + b^n = c^n$
the program should print, "Holy smokes, Fermat was wrong!"
. Otherwise the program should print, "No, that doesn't work."
Write a function that prompts the user to input values for a
, b
, c
and n
, converts them to integers, and uses checkFermat()
to check whether they violate Fermat's theorem.
If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are 1 inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle.
If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a 'degenerate' triangle.)
isTriangle()
that takes three integers as arguments, and that prints either Yes
or No
, depending on whether you can or cannot form a triangle from sticks with the given lengths.triangleTest()
that prompts the user to input three stick lengths, converts them to integers, and uses isTriangle()
to check whether sticks with the given lengths can form a triangle.