Conditionals

Use the if statement to make decisions in your code that affect the execution flow of the program.

Review

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

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.

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

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.

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.

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

Boolean Expressions

A boolean expression is a binary expression that evaluates to either True or False.

True and False are both of type bool.

Relational Operators

To form a boolean expression use the relational operators:

Careful not to use = instead of == for equality, since that would cause a hard to find error.

Logical Operators

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

Conditional Execution

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

If you are not ready to implement the body use pass as a placeholder.

elif

Use elif to explore alternative branches or possiblities. Use as many as you need.

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.

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.

Nice shortcut

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.

Recursion

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.

Let's look at another example that prints a string a number of times.

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

Infinite recursion

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.

Keyboard input

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.

Practice problems

Create a separate Python source file (.py) in VSC to complete each exercise.


p1: timeModule.py

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.

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.


p2: fermat.py

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."


p3: fermatInput.py

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.


p4: isTriangle.py

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

  1. Write a function named 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.
  1. Write a function 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.
[Functions] [TOC] [Functions Return]