Python Flow Control

Python if, if…else, if…elif…else and Nested if Statement

The most crucial feature of practically all programming languages is the decision-making process. Decision-making, as the name implies, allows us to run a specific piece of code for concluding a specific decision. The foundation of decision-making is condition checking. In Python, decision-making is performed by using conditional statements. One such famous conditional statement is the Python if statement. This article will provide us an insight into the if statement, its different types, and its applications along with few examples.

Definition

  • Python if statement along with its variants is used for the decision-making process.
  • The Python if statement is used to determine whether or not a specific statement or set of statements will be performed.

What is Python if Statement?

Syntax

                    

if condition:
     statements(s)

Flowchart

Python if statement

The if statement in Python is used to make decisions. It comprises of a piece of code that only executes when the if statement’s condition is TRUE. If the condition is FALSE, then the condition will not be executed.

Note – The indentation of the body of the loop in Python indicates the content of the if statement. It is necessary to indent the content after the ‘if statement’ has been declared. The body begins with an indentation and ends with the first unindented line.

Python supports the standard mathematical logical conditions:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be utilized in a variety of ways in the if statement.

Example 1

                    

# Python program to illustrate different if conditions
age = 16
limit = 25

if (age == 16):
    print('Age is correct as mentioned')

if (age < 25):
    print('Below age')

if (age > 10):
    print('Teen')

if (age <= limit):
    print('Under age limit')

if (age >= limit):  # will not be printed because the condition is FALSE
    print('Above limit')

Output

                    

Age is correct as mentioned
Below age
Teen
Under age limit

Example 2

                    

# Python program to illustrate if the number is even using if statement
num = int(input('Enter a number:'))

if (num%2 == 0):
    print('Number is Even')

Output

                    

Enter a number:10
Number is Even

In Python, there are a total of 5 different if statement variants. Let us look at them one by one.

Python if…else statement

Syntax

                    

if condition:
     statements(s)
else:
     statements(s)

Flowchart –

Python if else flowchart

The if-else statement comprises of 2 blocks of statements out of which the first set of code executes only when the if statement’s condition is true. If the condition is false, then the statements in the body of the else section will be executed.

Example

                    

# Python program to compare between subject marks
history = 45
science = 57

if (history > science):
     print('History marks greater than Science')
else:
     print('Science marks greater than History')

Output

                    

Science marks greater than History

In the above example, if the history marks are greater than science marks, the if condition will be satisfied i.e. TRUE and the corresponding print statement will be executed. If the ‘if condition’ does not satisfy i.e. FALSE, then the body of the else loop will be executed.

Python if…elif…else statement

A user can choose from a variety of alternatives here. In this variant of ‘if statement’, there are many else if conditions declared. If the first condition does not satisfy then the next condition is executed. But if this condition also does not satisfy then the next condition is executed. Let us look at the syntax and the flowchart of if…elif…else statement.

Syntax

                    

if condition1:
      statements(s)   # body of if
elif condition2:
      statements(s)   # body of elif
elif condition3:
      statements(s)   # body of elif
else:
      statements(s)   # body of else

Note – elif is short for else if. If the condition for if is FALSE then the elif condition is checked and executed if found TRUE or, the statements after elif are executed.

Flowchart –

Python If elif else flowchart

Example

                    

# Python program to check student grade based on the marks
marks = int(input('Enter marks from 0-50: '))

if (marks<20):
    print('Student Failed')
elif (marks>20 and marks<40):
    print('Student passed with B Grade')
else:
    print('Student passed with A Grade')

Output

                    

Enter marks from 0-50: 35
Student passed with B Grade

Python Nested if statement

We can have an if…else statement inside another if…else statement. This is called as nesting of loops. Python provides us with the nesting method. These statements can be nested inside each other in any order. The only way to determine the depth of nesting is to use indentation. They can be perplexing, therefore they should be avoided until absolutely required.

Flowchart –

Python Nested if flowchart

Example

                    

# Python program to check sign of a user entered number
val = int(input('Enter a number: '))

if val>=0:
     if val == 0:
          print('Number is Zero')
     else:
          print('Number is positive')
else:
     print('Number is negative')

Output 1

                    

Enter a number: 24
Number is positive

Output 2

                    

Enter a number: 0
Number is Zero

Output 3

                    

Enter a number: -10
Number is negative

Python Shorthand if statement

Shorthand if can be used when only a single statement has to be processed inside the if block. The if statement and the statement can be on the same line. You can also use the else statement along with the shorthand if statement. The syntax is the same as mentioned below.

Syntax

                    

if condition: statement
else: statement

Example

                    

name = 'Rocky'

if name == 'Rocky': print('Hello Rocky')
else: print('What is your name?')

Output

Python Shorthand if-else statement

If there is only one statement to be executed in both the if and else blocks, this type of shorthand can be used to write the if-else statements on a single line.

Syntax

                    

statement_when_True if condition else statement_when_False

Example

                    

name = 'Tommy'

print('Hello Rocky') if name == 'Rocky' else print('What is your name?')

Output

                    

What is your name?

Frequently Asked Questions

Q1. How do you write an if statement in Python?

The Python if statement is used to determine whether or not a specific statement or set of statements will be performed. There are various methods to write an if statement in a Python program. These are –

  • Python if statement
  • Python if…else statement
  • Python if…elif…else statement
  • Python nested if statement
  • Python shorthand if statement
  • Python shorthand if…else statement

The simplest of them is the if statement. Its syntax is as follows –

                    

if condition:
     statements(s)

Example

                    

# Python program to check if 2 numbers are equal or not using if statement
a = 25
b = 25

if a == b:
    print('Values are equal')

Output

                    

Values are equal

Another most common if statement in Python is the if…else statement.

Example

                    

# Python program to demonstrate if…else
ch = input('Enter any character: ')
vow = 'aeiouAEIOU'

if ch in vow:
     print("Entered character is a vowel")
else:
     print("Entered character is not a vowel")

Output

                    

Enter any character: f
Entered character is not a vowel

Q2. Why do we use if statements in Python?

Every day, we analyze our real-time circumstances and make some decisions, based on which we will decide further additional activities. As a result, our daily activities are entirely dependent on the decisions we make.

A similar situation exists in programming languages, where we must make judgments and the program will run based on those decisions.

The if statement in Python is used for the purpose of making decisions. The Python if statement comprises of a piece of code that only executes when the if statement’s condition is TRUE. If the condition is FALSE, the else statement, which includes code for the else condition, is executed.

Q3. What is an example of an if statement in Python?

Python if statements are used when there arises a situation to choose between multiple options depending on the results of the conditionality. For example, a number entered by the user needs to be categorized as a positive number or negative number. For such a case, the if statement provides a path for implementation.

Example 1

                    

# Python program to check if number is positive or negative
num = float(input('Enter a number: '))

if num >= 0:
     print('Positive Number found')
else:
     print('Negative Number found')

Output

                    

Enter a number: 10.4
Positive Number found

Example

                    

# Python program to check voting eligibility
age = int(input("Enter your age: "))

if age >=18:
     print("Eligible for Voting")
else:
     print("Not eligible for voting")

Output –

                    

Enter your age: 45
Eligible for Voting

Another example where if statements can be used is when we want to categorize the price of an item.

Example 3

                    

# Python program to indicate toy price using if…elif…else
toy_price = 380

if toy_price > 500:
     print('Toy price is Greater than Rs 500')
elif toy_price < 500:
     print('Toy price is Less than Rs 500')
else:
     print('Toy price is Rs 500')

Output

                    

Toy price is Less than Rs 500

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.