• 6 hours
  • Easy

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 4/11/24

Control Your Program Flow Using Conditionals

What Is Program Flow?

Program flow is the order in which lines of code are executed. Some lines will only be read once, others multiple times, and others still may be skipped entirely, depending on how you've programmed them.

In this first chapter on program flow, we will look at how to program your code using conditional statements.

Conditionals are ways to control the logic and flow of your code using different conditions. You make decisions based on conditions in your daily life all the time.

For example: If it's sunny outside, go to the beach. In this scenario, whether or not you go to the beach is dependent on the weather as a condition. 

Let's see how this type of logic works in code.

Define Conditions With If/Else Statements

One of the most important and basic building blocks of a conditional flow is the if statement.

With an if statement, you can run certain lines of code only if a certain condition is true. If that condition is false, the code won't run. 

Here's a weather example:

if sunny:
    print("go to the beach!")

Line 2 will only execute if the condition  sunny  is  True .

Sounds simple enough, so where does "else" come in?

Now let's expand the weather example to include an else clause:

If it's sunny outside, go to the beach.
Else (for example, if it's raining), stay inside!

When using if/else statements in Python, the syntax looks like this:

if my_boolean:
    # execute code when my_boolean is True
else:
    # execute code when my_boolean is False

So to only print a statement under a certain condition, you can do the following:

sunny = True
 
if sunny:
    print("go to the beach!")
else:
    print("stay inside!")

In this code snippet, since  sunny  is true,  you will see  go to the beach!  in your terminal. If it were set to false, the code would print  stay inside! .

Define Alternative Conditions by Adding an Elif Clause

An if/elif/else statement allows you to define multiple conditions. The elif keyword allows you to add as many conditions as you’d like. You then end the statement with an else clause.

Let’s say you want to go to the beach if it’s warm outside, build a snowman if it’s snowing, or otherwise stay home. You can code that with the following syntax:

sunny = False
snowing = True
 
if sunny:
    print("go to the beach!")
elif snowing:
    print("build a snowman")
else:
    print("stay inside!")

This code will first check if  sunny  is true, and because it is false, it will then check if  snowing  is true. Because  snowing  is True, the code will print  build a snowman . But if  snowing  were also false, the program would execute the final else statement and print  stay inside! .

Define Multiple Conditions With Logical Operators

If you want to check multiple conditions for a single outcome in the same if statement, you can use logical operators:

  • and : check if two conditions are both true.

  • or : check if at least one condition is true.

  • not: check if a condition is not true (i.e., false). 

These operators can be mixed and matched for your needs.

Let’s say you want to go to the beach only if it’s sunny and a weekend, but if it’s sunny and a weekday, you need to be at work.

is_sunny = True
is_weekday = False

if is_sunny and not is_weekday:
    print("go to the beach!")
elif is_sunny and is_weekday:
    print("go to work")
else:
    print("stay inside!")

Define Complex Conditions With Comparative Expressions

Comparative expressions let you compare different expressions to each other and evaluate whether that expression is true or false.

If you have two values a and b , you can use the following comparison operators in Python: 

  • Equals: a  ==  b

  • Not Equals: a  !=  b

  • Less than: a  <  b

  • Less than or equal to: a  <=  b

  • Greater than: a  >  b

  • Greater than or equal to: a  >=  b 

For example:

number_of_seats = 30;
number_of_guests = 25;

if number_of_guests < number_of_seats:
    # allow more guests
else: 
    # do not allow any more guests

You can mix and match any number of these tools to have really complex and intricate code functionality.

Level-Up: Control Your Program Flow Using Conditionals

Context:

If you do this activity, you will progress. Else, you will miss out on a great opportunity. It's time to practice with conditions! 😁

You will create a calculator that allows performing a simple operation between two numbers. So, you will need to create two variables to store the two numbers, and one variable to store the symbol representing the operation to be performed. You will first create a conditional structure that will check the validity of the variables and the symbol. Then, you will create a second conditional structure to perform the operation based on the chosen symbol. Don't worry, the exercise will be guided by questions. Let's get started! It's your turn to play!

Instructions:

  1. Create two variables  left_number  and  right_number  , and assign each of them an integer.

  2. Create a variable  symbol  to store the operation symbol (+, -, *, or /).

  3. Create a last variable  result  initialized to 0, which will then contain the result of the calculation.

  4. Check that both variables  left_number  and  right_number  are indeed integers. If one or both are not integers, display a corresponding error message and exit the program. (Hint: Use the  isinstance()  function)

  5. Check that the symbol stored in the  symbol  variable corresponds to one of the 4 allowed operations (`+`, `-`, `*`, or `/`) using  match. If the symbol is incorrect, display a corresponding error message, and exit the program.

  6. Note that dividing a number by 0 is impossible, so you need to provide an additional conditional structure to check this case in the  match  structure. Use if-else conditions to perform this operation; if there is a division by 0, display  Error: division by zero is not allowed.  , otherwise store the calculation in the  result  variable.

  7. Display the result contained in the  result  variable.

Once you have completed the exercise, you can run the following command in the VS code terminal  pytest tests.py

Let’s Recap!

  • If/else statements help you define certain conditions for when code is executed.

  • The elif keyword allows you to use multiple conditions.

  • You can group different conditions together using  and ,  or , and  not .

  • Comparative expressions use comparison operator like  <  and  >  help you compare multiple variables.

In the next chapter, you’ll learn how to repeat code tasks using loops.

Example of certificate of achievement
Example of certificate of achievement