5.5. Conditionals

At the beginning of this chapter, we presented an example of an app that tracks overdue library books.

Example

Consider an application that reminds you when you have an overdue book. The app sends you a message only if the due date has passed and you have not returned the book.

The app sends a message to the user if the condition “the book is overdue” is true.

In Python and other programming languages, conditional statements are used to either run or skip certain parts of the code. If a condition is True, then the program runs a specific block of code. Otherwise, the program ignores that code and performs a different action.

5.5.1. if Statements

The most basic form of a conditional is an if statement. Here’s how to create one in Python:

1
2
3
4
5
if condition:
   # Code statement 1
   # Code statement 2
   # Code statement 3
   # etc.

Syntax Notes:

  1. The if statement consists of a header line and a body. The header line begins with the keyword if followed by a condition and then a colon (:).

  2. condition is a boolean expression, which returns either True or False. Examples include name == 'Jack' or points > 10.

  3. The statements underneath the header make up a code block (lines 2 - 5). Note that these statements MUST be indented, and the code block can be any size.

  4. The indented code runs if the condition evaluates to True. If the condition is False, this code gets ignored.

  5. The first unindented line marks the end of the if statement.

Here is an example that checks the length of a string:

1
2
3
4
text = "Don't Panic"

if len(text) >= 10:
   print(text, "has more than 10 characters.")

len(text) returns the number of characters in the string stored in text. If the comparison is True, then line 4 prints the message to the console. If the string is less than 10 characters long, then no message appears.

Note

Should you indent with tabs or spaces? This question usually starts BIG arguments within the programming world (think Marvel vs. DC or Hermione Granger marrying Harry instead of Ron).

Many code editors automatically indent the lines within an if block, so most of the time you won’t need to worry about how far to move in the cursor. However, here are the accepted guidelines for Python:

  1. Use SPACES, not tabs

  2. Four spaces are preferred

  3. Indentation must be consistent within a code block.

5.5.1.1. Try It!

In the editor below, try the following:

  1. Run the code as-is.

  2. Assign num a positive value, then re-run the code.

  3. Indent line 6 to match line 4, then re-run the code. How did the output change?

  4. Change the condition to print a message when num is positive.

  5. Advanced: Use the modulus operator (%) in line 3 in order to print a message when num is even.

5.5.2. else Clause

The example above either prints a message or nothing at all, depending on the value of num. What if we ALWAYS want to print something, but we want the message to change based on the value of num?

Adding an else clause to an if statement allows us to include code that runs when the condition is False.

Example

  1. Run the following code as-is and examine the output.

  2. Change line 2 to book_status = 'overdue' and run the code again.

  3. How does the output change?

This structure is known as an if/else statement, and it allows our program to branch. The flow of the program takes one of two paths when it reaches a conditional, depending on whether the condition is True or False.

A diagram showing how the flow of a program branches based on the value of the condition in an if-else statement. If the condition is true, one code block executes. If the condition is false, a different code block executes.

5.5.3. Check Your Understanding

Use the code below to answer the following questions:

1
2
3
4
5
6
name = input('Please enter a username: ')

if len(name) >= 8:
   print("Welcome, " + name + "!")
else:
   print("Invalid username.")

Question

What message gets printed if the user enters "Aahliyah" as their username?

  1. Invalid username.
  2. Welcome, name!
  3. Welcome, Aahliyah!
  4. Nothing is printed.

Question

Assume that you replace line 3 with if len(name) < 5:. When would Invalid username get printed?

  1. For any name with 4 characters or less
  2. For any name with 5 characters or less
  3. For any name with 4 characters or more
  4. For any name with 5 characters or more

Question

If you want to print the welcome message for any username SHORTER than 20 characters, how should you change line 3?

  1. if len(name) > 20:
  2. if len(name) >= 20:
  3. if len(name) < 20:
  4. if len(name) <= 20: