CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Control Flows – The if Statement

When we write the code in any language, we always write portion of the code to execute depending on certain condition(s). This will give more control and easy to manage the code. The statement which control the flow of the execution is control or conditional statement.

One of such control statement is; the if statement. This is a compound statement where it allows to execute the statements by give condition.

The if Statement

The conditional statement if evaluates the given expression and allows to execute the statements in it’s code block. Even we can attach else statement to the if statement. When the expression is evaluated; the code within the if statement will execute when the expression value is TRUE. Otherwise, the statements within the else statement will execute.

>>> a = 20
>>> if a > 0:
...    print("Positive number")
... else:
...    print("Negative number")
... 
Positive number
>>>

else statement is optional; if it presents, Python will execute the statements given in it’s code block when the expression’s result is FALSE. If else statement NOT exists, Python will execute the statements after the if statement.

if within if

We can combine if statements to evaluate multiple expressions. Depending on the result of the expression, the code within the particular if block will be executed. Important thing to remember here is, maintain the proper indentation when using control statements within the control statement. The results will be unexpected, if NO proper indentation maintained.

>>> a = 20
>>> if a > 0:
...    print("Positive number")
...    if a%2 == 0:
...       print("Even number")
... else:
...    print("Negative number")
... 
Positive number
Even number
>>>

if within elseelif Statement

We can use if statement within else statement. This also useful to evaluate multiple expressions. This is equivalent to the switch and case statements in other languages.

>>> a = 1
>>> if a == 1:
...    print("One")
... else:
...    if a == 2:
...       print("Two")
...    else:
...       if a == 3:
...          print("Three")
... 
One
>>>

Observe that, if statements are properly indented to keep them aligned with respective else statements. If you miss the indentation, you will see the wrong results. To simplify this, Python provides elif statement; this is the short form of “else if” statement.

The simplified version of the above code, we can re-write as below.

>>> a = 2
>>> if a == 1:
...    print("One")
... elif a == 2:
...   print("Two")
... elif a == 3:
...   print("Three")
... 
Two
>>>

Observe that, how the code is neatly organized when using elif statement.

We will discuss more topics as we go.

/Shijit/

Python – Control Flows – The if Statement

2 thoughts on “Python – Control Flows – The if Statement

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top