Learning objectives
Now that we know a bit more about functions, we are ready to take the next steps and see how Python implements different aspects of the control flow that we learned about in the main text on the level of pseudocode.
For example, consider the following pseudocode function Min2()
that we introduced in the core text to find the minimum of two input integers.
Min2(a, b) if a < b return a else return b
In this lesson, we will explore Python’s syntax for if and else statements.
Code along summary
Set up
Create a new folder called conditionals
in your python/src
directory, and then create a new file within the python/src/conditionals
folder called main.py
, which we will edit in this lesson. We will add starter code to main.py
as follows.
def main(): print("Conditionals in Python.") if __name__ == "__main__": main()
Taking the minimum of two integers
Just as we used indentation to define blocks of code in Python functions, we will use indentation to enclose if statements. As a result, our
pseudocode function does not change very much when we convert it to Python. Note that we include type hints as well as a docstring for best practices as described in the previous code along.Min2()
def min_2(a: int, b: int) -> int: """ Takes two integers as input and returns their minimum. Parameters: - a (int): first integer - b (int): second integer Returns: int: minimum of a and b """ if a < b: return a else: return b
We will now call min_2()
. Add the following code along with min_2()
to main.py
.
def main(): print("Conditionals in Python.") print("The minimum of 3 and 4 is", min_2(3, 4))
STOP: Let’s run this code. Open a command line terminal and navigate into the folder containing your code by executing the command. Then, run the code by executing the command
cd python/src/conditionals
(Windows) or
python main.py
python3 main.py
(macOS/Linux).
Note: Python includes a built-in function calledmin()
that takes an arbitrary number of numeric variables as input and returns their minimum; we will say more about it in a later section.
From two cases to three: introducing elif (“else if”)
We now consider a function which_is_greater()
returns 0 if two input integers are equal, 1 if the first input integer is larger, and -1 if the second input integer is larger. Because it considers three possible cases, which_is_greater()
uses an elif
statement (which represents “else if”) between the if
statement and the else
statement. In general, we could use as many intermediate elif
statements that we like when representing multiple cases. Note below that when we are comparing two integers for equality, we use double equals (==
), as the single equals symbol is reserved for setting the value of a variable.
def which_is_greater(x: int, y: int) -> int: """ Takes two integers as input and returns 1 if the first input is larger, -1 if the second input is larger, and 0 if they are equal. Parameters: - x (int): first integer - y (int): second integer Returns: int: 1 if x is greater than y, -1 if y is greater than x, and 0 if x and y are equal """ # we need three cases if x == y: return 0 elif x > y: return 1 else: # if we make it into this else block, we know that y > x return -1
STOP: Inmain.py
, confirm thatwhich_is_greater()
is working by printing out the values ofwhich_is_greater(3, 5)
,which_is_greater(42, 42)
, andwhich_is_greater(-2, -7)
indef main()
.
A function determining if two integers have the same sign
Let’s consider another example. In the following function same_sign()
, we would like to quickly determine if two input integers x
and y
have the same sign (we will apply a convention treating 0 as having the same sign as all integers). One way that we could implement same_sign()
would be to have three cases:
x
andy
are both greater than or equal to zero (returnTrue
);x
andy
are both less than or equal to zero (returnTrue
);- the remaining default case, in which
x
andy
must have opposite sign (returnFalse
).
The code below implements this idea. Note that we use the comparison operator >=
instead of the symbol ≥
that you are most likely familiar with, since the former is easier to type. Furthermore, the code below allows us to provide a preview of the and
keyword, which joins two boolean expressions and is only True
if both of the expressions that it joins together are True
.
def same_sign(x:int, y:int) -> bool: """ Takes two integers as input and returns True if they have the same sign, and False if they have different signs. Parameters: - x (int): first integer - y (int): second integer Returns: bool: True if x and y have the same sign, False otherwise """ if x >= 0 and y >= 0: # >= is "greater than or equal" return True elif x <= 0 and y <= 0: return True else: return False
However, if we consider the product x * y
, then this product is always at least equal to zero in cases 1 and 2 and always negative in case 3. As a result, we can simplify our implementation of same_sign()
to have just two cases, as shown below. If the product x * y
is greater than or equal to zero, then we enter the if block and return True
; otherwise, we enter the else block and return False
.
def same_sign(x:int, y:int) -> bool: """ Takes two integers as input and returns True if they have the same sign, and False if they have different signs. Parameters: - x (int): first integer - y (int): second integer Returns: bool: True if x and y have the same sign, False otherwise """ if x * y >= 0: # >= is "greater than or equal" return True else: return False
Technically, we don’t need an else block in the above code, because if the condition x * y >= 0
is not True
, then we will continue past the if block, and we know that we can simply return False
. We can therefore simplify same_sign()
a bit further by removing the else statement entirely.
def same_sign(x: int, y: int) -> bool: """ Takes two integers as input and returns True if they have the same sign, and False if they have different signs. Parameters: - x (int): first integer - y (int): second integer Returns: bool: True if x and y have the same sign, False otherwise """ # x and y have the same sign when x*y is >= 0 if x * y >= 0: return True # I know that x*y < 0 return False
Note: For the precocious, we can optimizesame_sign()
even further by writing only the single linereturn x * y >= 0
. This is because the expressionx * y >= 0
has the valueTrue
when the product ofx
andy
is at least zero, andFalse
otherwise.
STOP: Inmain.py
, confirm thatsame_sign()
is working by printing out the values ofsame_sign(3, 5)
,same_sign(-2, 0)
, andsame_sign(-23, 17)
indef main()
. These function calls should printTrue
,True
, andFalse
, respectively.
A function taking the positive difference between two integers
Our final function, positive_difference()
, again takes two integers, and it returns the absolute value of the difference between the two integers. A simple way to write this function is to consider three cases that are analogous to the three cases in which_is_greater()
.
def positive_difference(a:int, b:int) -> int: """ Takes two integers as input and returns the absolute value of their difference. Parameters: - a (int): first integer - b (int): second integer Returns: int: positive difference of a and b """ if a == b: return 0 elif a > b: return a - b else: # can safely infer that b > a return b - a
STOP: How could we implementpositive_difference()
using only two cases?
Although you may have noticed a way of writing positive_difference()
using only two cases, it turns out that we don’t need an if statement at all. Python includes a built-in function abs()
that takes a number as input and returns its absolute value. Here, regardless of the case, positive_difference is always returning the absolute value of the difference between a
and b
, and so we can simply return abs(a-b)
. This example shows that sometimes, even if it might seem obvious that we should use an if statement, we don’t necessarily need one.
def positive_difference(a:int, b:int) -> int: """ Takes two integers as input and returns the absolute value of their difference. Parameters: - a (int): first integer - b (int): second integer Returns: int: positive difference of a and b """ return abs(a-b)
STOP: Inmain.py
, confirm thatpositive_difference()
is working by printing out the values ofpositive_difference(3, 5)
,positive_difference(2, -4)
, andpositive_difference(-7, 0)
indef main()
. These print statements should print 2, 6, and 7, respectively.
Index of comparison operators
In this lesson, we have seen a collection of comparison operators, which we will use throughout the course. Below, we list a collection of the most common comparison operators used in Python.
> : greater than < : less than >= : greater than or equal to <= : less than or equal to == : equal to != : not equal to
>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to==
: equal to
Looking ahead
Now that we can handle branching into multiple cases based on some condition, we are ready to see how Python implements loops, in which the same action is taken multiple times until a condition is reached. We start in the next lesson with while loops.
Check your work from the code along
We provide autograders in the window below (or via a direct link) allowing you to check your work for the following functions:
min_2()
which_is_greater()
same_sign()
positive_difference()