Skip to content

Chapter 5 (Conditionals)

CSP-PC edited this page Jun 20, 2022 · 7 revisions

Program Flow

So far, you've learned the fundamental building blocks of Python. That means you can make simple processes, such as this Addition Calculator shown below:

print("Addition Calculator")
num_1 = int(input("Enter number 1: "))
num_2 = int(input("Enter number 2: "))
result = num_1 + num_2
print("The answer is " + str(result))

Like every program you have made before, the above lines of code will run from the topmost line to the bottommost line, in that order, and every single line will be run.

However, for many programs, we will not want every single line to run -- sometimes, we will want the program behavior to change based on the user's input, or a particular value of a variable. For example, if we wanted the calculator to be able to calculate an operation of the user's choosing, there would be no way to do it using what we have learned so far. An example of a (feeble) attempt at doing so can be seen below:

#Python runs all the lines in order. The final value of result will always be num_1 divided by num_2, since it replaces the previous values in the last line
result = num_1 + num_2
result = num_1 - num_2
result = num_1 * num_2
result = num_1 / num_2

To model more complex behavior, we will need techniques that allow us to skip lines, or run some lines more than once. In this chapter as well as the subsequent two, you will learn these techniques.

Conditionals and Conditions

In this chapter, we will be looking at conditionals -- that is, making some code run only if some condition is satisfied. Before we look at the syntax of doing so, we need to understand how to define conditions. In Python, conditions should always resolve to a boolean value -- True if the condition is met and False if it is not.

A vast majority of conditions you will encounter will involve comparisons, such as checking whether a number is more than a certain value, or if a user submitted password is equal to the correct password. In Python, there are six comparison operators, as shown below:

Operation Symbol Example that yields True Example that yields False
Equal == (1 + 2) == 3 "abc" == "ab"
Not Equal != 1 != 2 0 != False
More Than > 4 > 3.5 "a" > "b"
More Than or Equal To >= 5 + 4 >= 9 11 - 5 >= 6.1
Less Than < 2.25 < 2.4 "abcd" < "a"
Less Than or Equal To <= 2 + 3 <= 5.5 True <= False

As can be seen in the above table, non-numerical types (str and bool) have some interesting properties when comparison operators are used on them.

  • str variables are compared based on lexicographical order, or to put it simply, the order they would appear in a dictionary. The first character is compared, and the one that comes first in the alphabet is considered to be less than the other. If they are the same, the second character is compared, and so on. Note that this assumes uniform case and that we are comparing letters -- the process gets more complicated with non-alphabetic characters and will not be explained here.
  • bool variables are converted to numerical values: True is given 1 and False is given 0. Hence, the statements True == 1, False < 0.5 and True > False will give True. However, usage of this behavior is not advised as it can be confusing to whoever is trying to read your code.

Attempting to compare strings to numerical values will yield an error:

>>> 1 < "a"
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    1 < "a"
TypeError: '<' not supported between instances of 'int' and 'str'

Other than comparison operators, another commonly used condition is that using the in keyword. The in keyword can only be used for certain types, the only relevant one for us right now being str. Below shows some examples of how the in keyword behaves:

>>> "abc" in "abcd"
True
>>> "abcd" in "abdc"
False

The if statement

The structure of an if statement goes:

if(condition):
    #These lines will only execute if condition is True

Note that the spaces before the lines of code inside the if statement are important! Python uses the tab character to distinguish between sections of your code, known as blocks. Essentially, using tabs before the relevant lines of code is how Python knows whether you want the line to always run, or to only run as part of the condition. Similarly, do not forget the colon (:) after the if statement, as it tells Python that you are beginning the if block. If you remember the colon, Python should indent the lines that follow for you.

A simple example is shown below:

>>> a = 1
>>> if a == 1:
        print("The condition is true!")
The condition is true!

The elif statement

elif is short for "else if". These statements must be placed after an if statement, and code within the elif block will run only if the condition for all above if and elif blocks are False and their own condition is true. For example:

>>> a = 3
>>> if a < 4: 
        print("a is less than 4")
    elif a < 5:
        print("a is less than 5")
a is less than 4

In the above example, the condition a < 4 is found to be True, so the code within the if block runs. Consequently, the entire elif block is skipped, and the second message is not printed, despite the condition a < 5 being True. Hence, in the following example:

>>> a = 3
>>> if a == 4: 
        print("a is equal to 4")
    elif a < 4:
        print("a is less than 4")
a is less than 4

The first condition of a == 4 is False, so Python continues and checks the condition for the elif block a < 4, which is found to be True. Hence, the second statement is printed.

At the beginning of this section, it was mentioned that elif blocks will run if all above blocks have their conditions False. Indeed, after the initial if block, you may have as many elif statements as you want, which will be checked in order. Another way of remembering this is that only the first block that Python comes across with its condition met will be run -- anything that comes after will be immediately skipped.

For example, you could run the following code to check if a user input value is higher or lower than a certain number:

ans = 40
guess = int(input("Guess a whole number between 1 and 100: "))
if guess > ans:
    print("Too high!")
elif guess < ans:
    print("Too low!")
elif guess == ans:
    print("Correct!")

The else statement

Notice that in the above example, by the time we reach the condition guess == ans, it must always be True, since the guessed value is not higher than or lower than the correct answer. Thus, in such a scenario, we can instead use an else block.

You may choose to write an else block after your if statement as well as as many elif statements as you wish. The else block will run if none of the previous statements have run: it is identical to an elif statement with condition of simply True. Since nothing after the else block will ever run (remember the rule of only one block in the whole chain ever running), the else block must be placed at the end.

The above example changed to use an else block would look like the following:

ans = 40
guess = int(input("Guess a whole number between 1 and 100: "))
if guess > ans:
    print("Too high!")
elif guess < ans:
    print("Too low!")
else:
    print("Correct!")

With that, you have learned the whole if-elif-else structure of conditional blocks!

Clone this wiki locally