Conditionals in Python

Code along video

Although we strongly suggest coding along with us by following the video above, you can find completed code from the code along in our course code repository.

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 Min2() 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.

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 cd python/src/conditionals. Then, run the code by executing the command python main.py (Windows) or python3 main.py (macOS/Linux).
Click Run 👇 to try it!
Note: Python includes a built-in function called min() 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: In main.py, confirm that which_is_greater() is working by printing out the values of which_is_greater(3, 5), which_is_greater(42, 42), and which_is_greater(-2, -7) in def main().
Click Run 👇 to try it!

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:

  1. x and y are both greater than or equal to zero (return True);
  2. x and y are both less than or equal to zero (return True);
  3. the remaining default case, in which x and y must have opposite sign (return False).

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 optimize same_sign() even further by writing only the single line return x * y >= 0. This is because the expression x * y >= 0 has the value True when the product of x and y is at least zero, and False otherwise.
STOP: In main.py, confirm that same_sign() is working by printing out the values of same_sign(3, 5), same_sign(-2, 0), and same_sign(-23, 17) in def main(). These function calls should print True, True, and False, respectively.
Click Run 👇 to try it!

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()

powered by Advanced iFrame


Scroll to Top
Programming for Lovers banner no background
programming for lovers logo cropped

Join our community!

programming for lovers logo cropped
Programming for Lovers banner no background

Join our community!