Mark As Completed Discussion

In this lesson, we will discuss the flow of execution of programs, with a focus on the following key points,

  1. How can the execution flow of a program be controlled?
  2. Working with if/else and try/catch statements to establish control flow in programs.

For the Javascript version of this lesson, please click here.

In previous lessons, we learned about variables, data types, and performing different operations using variables. This lesson focuses on the control flow of a program, which is the concept of controlling the behavior of the program during its execution. The control flow of a program can be specified by several pre-defined elements in programming languages. In this lesson, we will discuss two of these elements, if/else and try/catch statements.

Control Flow of a Program

Control flow of a program refers to the order of execution of various code elements in the program. This means that we can ask the program to perform certain actions when some specific condition is triggered. This allows the program to make decisions according to different situations that it may encounter during its execution.

The first control flow element that we will discuss is if/else statements. They allow the programmer to specify certain decisions within a program and execute different statements in a program under various specified conditions. The second control flow element discussed will be try/catch statements. They are responsible for handling errors and exceptions that may arise in a program. They change the flow of execution whenever such a situation occurs so that the flow of execution of the program is not disturbed.

If/Else Statements

If/else statements can be best visualized and understood in the form of flow chart diagrams. For example, suppose we want to determine if a number is odd or even, and display a helpful message accordingly. In a sequential program, we cannot do this as it executes the program in a single flow, executing all statements. However, here we need different path flows for different outcomes, as shown below.

If/Else Statements

Thus, we need to be able to control the flow of the program by specifying that if the number is even print "x is even" else the number is odd print "x is odd". Depending on the number, the decision and output will be shown automatically through the execution.

Below is another example, where multiple execution paths are defined. This allows for specification of more than 2 different conditions.

If/Else Statements

Let's see how these concepts take effect in Python and JavaScript.

If/else Statements in Python

Python has an if keyword which executes this task. In Python, the if keyword follows an expression, and the body of the if statement is denoted by an indentation (4 spaces or a single tab). The body may contain one or several statements which need to be evaluated under that condition. In general, we have the syntax as,

SNIPPET
1if expression:
2    statement

The program evaluates the expression and will execute the statement if and only if the expression evaluates to True.

For the odd-even number example above, if statements in Python can be written as,

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

If we have multiple if statements, we can use the if-elif-else statement. This allows us to add more conditions. For the positive-negative-zero number example above, the Python code can be written as,

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

It is important to note that if conditions can exist independently (without elif or else) as well. However, an elif or else condition cannot work without an if condition beforehand.

Time for some practice questions!

Let's test your knowledge. Is this statement true or false?

There is a limit to the number of statements that we can have under an if block.

Press true if you believe the statement is correct, or false otherwise.

Build your intuition. Click the correct answer from the options.

What is wrong in the below code?

PYTHON
1length = 5
2breadth = 5
3
4if length == breadth
5    print("This is a square")
6else
7    print("This is not a square")

Click the option that best answers the question.

  • Missing `elif` condition
  • Round brackets missing for expression
  • Missing colon
  • Missing curly braces

Try/Catch Statements

When an error occurs during the execution of a program, the compiler of the programming language will stop execution and generate an error message. However, if we want to control what happens when an error occurs, we can use try/catch statements. They are triggered when an error occurs during the execution of the program. The try block allows to check for any errors and its body executes statements (if any) in case errors were not occured. The catch or except block allows the programmer to handle the error by telling the program what to do if the try block catches any errors.

Try/Catch Statements in Python

In Python, try and except keywords are used. A try block is specified using the try keyword, and the body of the try statement is denoted by an indentation. Its body can contain one or several statements which need to be evaluated if an exception does not occur. The except block is called if the try block catches any errors. Instead of halting the program, the statements in its body are executed, and the program flow will not break.

Let's consider an example. Suppose we try to print a variable x without declaring it. This will cause the program to raise an exception. But we do not want the program to stop, hence we use a try-except block to work around this problem.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Is this statement true or false?

Can we have an except block without declaring a try block beforehand?

Press true if you believe the statement is correct, or false otherwise.

Let's test your knowledge. Fill in the missing part by typing it in.

What will be the output of following code block in Python?

PYTHON
1try:
2    return 1
3except:
4    return 2

Write the missing line below.

Summary

In this lesson, we learned about controlling the flow of execution in programs, and how to make the program perform certain specific tasks under specific conditions. These control flow elements allow us to cater to any uncertain conditions that may occur on input (if/else statements) or during the execution of the program due to any flaws (try/catch statements). This is extremely powerful, as it is even used in complex applications such as those in artificial intelligence.

One Pager Cheat Sheet

  • In this lesson we will learn about controlling the flow of execution of programs in Javascript by using if/else and try/catch statements.
  • If/Else and Try/Catch statements are used to control the flow of a program and specify different code execution based on specified conditions and errors/exceptions.
  • Using If/Else Statements can control the flow of a program and automatically produce the desired output depending on certain conditions.
  • Python's if keyword is used to execute a certain task, by evaluating an expression and then executing the statement under the condition that the expression evaluates to True.
  • We can use if-elif-else to create multiple if statements and add conditions to our code.
  • It is important to note that an if condition must exist for any elif or else clauses to work.
  • No limit exists to the number of statements and code blocks (if, elif, else, etc.) that can be used under an if block.
  • The required colon (:) is missing from the if statements and else blocks in the code.
  • Using a try/catch statement allows us to handle errors by specifying what to do when an error occurs during the execution of a program.
  • Try/Catch statements in Python use the try and except keywords to allow programs to continue running, even when an exception is raised by the try block.
  • No except block can be called unless a try block has been declared and an exception has been raised, as the except block will not be executed without it.
  • The try block will always be executed and will return the value of 1, as the except block cannot be reached without a preceding try block.
  • We learned how to use if/else and try/catch statements to control program execution and handle any uncertain conditions that may arise when creating complex applications such as those used in artificial intelligence.