Learning All About Python if else Statement

Learning All About Python if else Statement

4 mins read798 Views Comment
clickHere
Updated on Jul 22, 2022 10:19 IST

The concept of Python if else statement works on the logic that a piece of code will be executed only if a certain condition is true, else not.

2022_07_MicrosoftTeams-image-4-3.jpg

Table of Contents

We will be covering the following sections today:

Python if Statement Syntax

Here’s the syntax for a simple if statement in Python:

if test expression:

    statement(s)

Python evaluates the test expression, and the statement(s) will be executed only if the test expression is True. In case the expression is False, the statement(s) is/are not executed.

In Python, the body of the if statement is indicated by the indentation. So, the first non-indented line marks the end of the body.

NOTE: In Python, non-zero values are interpreted as True, whereas None and 0 are interpreted as False.

Let’s look at the Python if Statement flowchart –

2022_07_Python-if-statement-image-1.jpg

Python if Statement Implementation Example

Example 1:

 
num = 7
if (num%2) == 0:
print(num, "is an even number.")
print("Even numbers are divible by 2.")
Copy code

Output 1:

2022_07_image-207.jpg

The condition (num % 2) == 0 is not true because (7 % 2) would give 1 (as remainder). So, the body of the statement is not executed and only the statement outside the body is displayed.

Example 2:

 
num = -1
if num < 0:
print(num, "is not a positive number.")
print("Numbers less than 0 are negative.")
Copy code

Output 2:

2022_07_image-208.jpg

The condition num < 0 is true because -1 < 0. So, the body of the statement is executed. The statement outside the body is displayed regardless.

Python if… else Statement Syntax

Here’s the syntax for if…else statement in Python:

 
if test expression:
Body of if
else:
Body of else
Copy code

The if…else statement evaluates the test expression and executes the body of if only when the test expression is True. In case the expression is False, the body of else will be executed.

Here too, indentation is used to separate the blocks of statements.

Let’s look at the Python if…else Statement flowchart –

2022_07_Python-if…else-Statement-flowchart-.jpg

Python if… else Statement Implementation Example

Example 1:

 
age = 11
if age >= 13 and age <= 19:
print("Person is a teenager")
else:
print("Person is not a teenager")
Copy code

Output 1:

2022_07_image-210.jpg

The condition is not true because the given age is 11. Hence, the body of the else statement is executed.

Example 2:

 
a = 2
if a >= 0:
print("This is a whole number")
else:
print("This is not a whole number")
Copy code

Output 2:

2022_07_image-211.jpg

We know that whole numbers are integer values greater than or equal to 0. The given input is clearly greater than 0. So, the condition is true. Therefore, the body of the if statement is executed.

Python if… elif… else Statement Syntax

Here’s the syntax for if…elif…else statement in Python:

 
if test expression 1:
Body of if
elif test expression 2:
Body of elif
else:
Body of else
Copy code
  • The if…elif…else statement first evaluates the test expression for the if statement and executes the body of if only when its test expression is True.
  • Otherwise, it moves on to the test expression of the elif statement. Note that elif stands for else-if. In case the elif condition is True, the body of elif is executed. There can be multiple elif statements.
  • Lastly, in case all the test expressions are False, the body of else will be executed.

Here too, indentation is used to separate the blocks of statements.

Let’s look at the Python if…elif…else Statement flowchart –

2022_07_Python-if…elif…else-Statement-flowchart-.jpg

Python if… elif… else Statement Implementation Example

Example:

 
age = 12
if age >= 13 and age <= 19:
print("Person is a teenager")
elif age >= 0 and age < 13:
print("Person is a prepubescent")
else:
print("Person is an adult")
Copy code

Output:

2022_07_image-212.jpg

As we can see from the code above, the age given is 12. So, the elif text expression is true. Therefore, the body of the elif statement is executed.

Nested if… else Statements

You can use any form of the if…else statement inside another if…else statement in Python. This concept is known as nesting in the programming world.

Any number of statements can be nested inside one another. The only way to separate the level of nesting is through indentation. Hence, indentation is extremely important in Python.

However, this can get easily complicated for large program codes. Hence, nesting is avoided unless necessary.

Example Syntax

Here’s an example syntax for nested if…else statements:

 
if test expression 1:
Body of if
if test expression 1.1:
Body of nested if
elif test expression 1.2:
Body of nested elif
else:
Body of nested else
else:
Body of else
Copy code
  • In the above snippet, the outer if statement consists of nested if…elif…else statements.
  • If the test expression for the outer if statement is True, only then will the nested if…elif…else statements be executed.
    • The body of nested if will be executed in case the nested if condition is True.
    • Otherwise, the body of nested elif will be executed in case the nested elif condition is True.
    • Otherwise, the body of nested else will be executed.
  • In case the test expression for the outer if statement is False, the body of outer else will be executed.

Nested if… else Statements Implementation Example

Example:

Consider the following example of a swimming camp being held for boys in a small town. Only boys under the age of 18 are allowed to join the camp and learn swimming free of cost. Let’s see how the nested if…else statements can be used to filter the people interested in attending the camp:

 
#Boys' Swimming Class
sex = input('Enter sex (M/F): ')
age = int(input('Enter age: '))
if sex == 'M':
if age >= 13 and age < 19:
print("Person is a teenager: allowed in group 1")
elif age >= 0 and age < 13:
print("Person is a prepubescent: allowed in group 2")
else:
print("Person is an adult: not allowed")
else:
print("Person is not allowed")
Copy code

Output:

2022_07_image-213.jpg

As we can see from the code above, the if condition is to check whether the person is male or not. Since this condition is True, we move on to the nested if…elif…else statements.

Now, we check the age of the male candidate, since the given age is greater than 18, the male is clearly an adult and hence, the body of the nested else is executed.

Endnotes

Hope this article was helpful for you to understand the various forms of if… else statements and how they are used for decision-making in Python. Want to learn more about and practice Python programming? Explore Python related articles here.

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments