...

/

The if Statement

The if Statement

Learn the usage and functionality of the 'if' statement in Python for controlling the flow of a program based on conditional expressions.

Structure

The simplest conditional statement that we can write is the if statement. It consists of two parts:

  1. The condition
  2. The code to be executed
Press + to interact

The : in the illustration above is necessary to specify the beginning of the if statement’s code to be executed. However, the parentheses, (), around the condition are optional. The code to be executed is indented at least one tab to the right.

The flow of an if Statement

An if statement runs like this:

if the condition holds True, execute the code to be executed. Otherwise, skip it and move on.

Let’s write a simple if statement that verifies the value of an integer variable:

Press + to interact
num = 5
if (num == 5):
print("The number is equal to 5")
if num > 5:
print("The number is greater than 5")

Our first condition simply checks whether the value of num is 5. Since this Boolean expression returns True, the compiler goes ahead and executes the print statement on line 4. Since num is not greater than 5, the second condition (line 6) returns False and line 7 is skipped. Also notice that the parentheses, (), around the conditions are optional.

As we can see, the print command inside the body of the if statement is indented to the right. If it wasn’t, there would be an error. Python puts a lot of emphasis on proper indentation.

Compound conditional statements

...
Access this course and 1400+ top-rated courses and projects.