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:
- The condition
- The code to be executed
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
thecondition
holdsTrue
, execute thecode to be executed
. Otherwise,skip it
and move on.
Let’s write a simple if
statement that verifies the value of an integer variable:
num = 5if (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.