Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Science USbreadcumb forward arrow iconPython If-Else Condition Explained [With Examples]

Python If-Else Condition Explained [With Examples]

Last updated:
3rd Aug, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Python If-Else Condition Explained [With Examples]

Decision-making is as crucial in any computer programming language as it is in life. In a programming language, decision-making is automated using conditional statements wherein Python evaluates the code to determine if it satisfies the specified conditions.

The conditions are evaluated and processed in true or false format. If found to be true, the program is executed as required. If found to be false, the statement included after the If condition is executed. If you are a beginner in python and data science, upGrad’s data science online programs can definitely help you dive deeper into the world of data and analytics.

There are six conditional statements in Python that are used in decision-making – 

  1. If statement
  2. If else statement
  3. Nested if statement
  4. If..elif ladder
  5. Short Hand if statement
  6. Short Hand if-else statement

Let’s understand how each of these works. 

Ads of upGrad blog

If Statement

The If statement is the most basic decision-making statement where the code is executed based on whether it satisfies the given condition. It has a code body that runs only if the condition included in the if statement is true. The statement can be single or a block.

The syntax for the if statement in Python is as follows. 

                   if condition :

                   # Statements to execute if the condition is true

Here’s an example for better understanding:

             a=30

              if (a==50) :      # True

              print (“Checking”)

              print (“This statement is true”)

As a is equal to 50, the condition is true. Thus, both expressions following the If body will be executed. If the above condition were false, the output would be blank. 

If Else Statement

This statement is used when both the true and the false parts of a given condition are specified to be executed. The statement inside the if block gets executed when the condition is true, and if false, the statement outside the if block gets executed. 

Here is the syntax of the If else condition: 

               if condition :

                       #Executes this block if the condition is true

                else :

                       #Executes this block if the condition is false

Python uses indentation to determine the scope of the code.

Here’s an example:

A = 100

if (A == 100):

   print (“Got a true expression value”)

else:

   print (“Got a false expression value”)

Since the above statement is true, the output will be “Got a true expression value.”

Here’s another program to check if a given character is a vowel or consonant:

# taking user input

ch = input(“Enter a character: “)

if(ch==’A’ or ch==’a’ or ch==’E’ or ch ==’e’ or ch==’I’

 or ch==’i’ or ch==’O’ or ch==’o’ or ch==’U’ or ch==’u’):

    print(ch, “is a Vowel”)

else:

    print(ch, “is a Consonant”)

Output 1: 

Enter a character: U

U is a Vowel

Output 2: 

Enter a character: b

b is a Consonant 

If..Elif..else Statement 

Here, the If condition is evaluated first. If it is false, the Elif statement will be executed, and if the Elif condition is false, the Else statement will be executed. 

 

The syntax is as follows: 

if condition :

    Body of if

elif condition :

    Body of elif

else: 

    Body of else

Here is a program to check if the given number is positive or

negative or zero. 

num = 4.5

# Try these two variations as well:

# num = 0

# num = -3.5

if num > 0:

    print(“Positive number”)

elif num == 0:

    print(“Zero”)

else:

    print(“Negative number”) 

When the num is positive, the output will be “Positive number”. If num is equal to 0, the output will be “Zero”. Similarly, if the num is negative, the output will be “Negative number.” 

Nested IF Statement

When an If the statement is lodged inside another If statement, it is known as a Nested IF statement. This is used when a variable has to be processed multiple times. The program can include If, If- else, and If..elif..else statements. The indentation (whitespace at the beginning) to determine the scope of each statement should be given primary importance in Nested If statements. 

Varying levels of nesting can be used, but high levels of nesting result in complex and tedious programs that are difficult to decipher.

Get data science certification online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Syntax:

if (condition1):

# Executes if condition 1 is true

if (condition 2):

  # Executes if condition 2 is true

  # Condition 2 ends here

#Condition 1 ends here

Here is a program to check if the given number is positive, negative, or zero.

num = float(input(“Enter the number: “))

if num >= 0:

    if num == 0:

        print(“Zero”)

    else:

        print(“Positive number”)

else:

    print(“Negative number”)

Output 1: 

Enter a number: 4

Positive number

Output 2:

Enter a number: -5

Negative number

Output 3:

Enter a number: 0

Zero

Both If and If-Else statements use the binary technique. If many conditions are involved, the If..elif..else statement should be used.

Here is a Python program for a Nested if..elif..else statement:

price = 50

quantity = 5

amount = price*quantity

if amount > 100:

    if amount > 500:

        print(“The amount is greater than 500”)

    else:

        if amount < 500 and amount > 400:

            print(“The amount is”)

        elif amount < 500 and amount > 300:

            print(“The amount is between 300 and 500”)

        else:

            print(” The amount is between 200 and 500″)

elif amount == 100:

    print(“Amount is 100”)

else:

    print(“Amount is less than 100”)

The output will be “The amount is between 200 and 500.”

Short Hand if statement

Short Hand if statement can be used when only one statement needs to be executed inside the if block.  You can mention this statement in the same line that holds the If statement. 

Here’s the syntax:

if condition: statement

An example program is given below for better understanding.

i=15

if i< 20: print (“i is less than 20″)

The output of the program will be “i is less than 20.”

Short Hand if-else statement

They are used to mention If-else statements in one line in which there is only one statement to execute in both if and else blocks. 

Here’s the syntax:

statement_when_True if condition else statement_when_False

Here’s a Python program to explain short hand If-else: 

i=30

print (True) if i<60 else print (False)

The output of the program will be True. 

Switch Case Statement in Python

Switch statements go in multiple ways to compare the value of a given variable with the values mentioned in the case statements. As there is no switch statement in Python, it uses dictionary mapping to impose a Switch Case. 

Example:

def Switch Example (argument):

       switcher = {

      0: ” This is case zero”,

“,

      1: “This is case one”,

      2: ” This is case two”,

}

    return switcher. get (argument. “nothing”)

if _name_ ==” _”main”_:

   argument = 1

    print (Switch Example (argument))

To summarize,

  • The If the condition is used to print the result when only one of the mentioned conditions is true or false. 
  • The If-else condition is used to print the statement when one of the conditions is false.
  • The Elif statement is used when there is a third possible outcome. Any number of Elif conditions can be used in a program. 
  • We can minimize the codes to be executed by declaring all the conditions in one statement. 
  • Nested if statements can be used to place one If condition inside another If statement. 

If you’d like to learn about similar Python concepts, we recommend you take upGrad’s 12-month Executive PG Program in Data Science course online from IIIT Bangalore. Apart from learning in-depth about Python, you also stand to master Tableau, Apache Hadoop, AWS, and MySQL, among others. 

Designed for freshers and mid-level managers, students can choose their desired specialization track from Data Science Generalist, Deep Learning, Natural Language Processing, Business Intelligence/Data Analytics, Business Analytics, and Data Engineering.

Ads of upGrad blog

The course comprises 60+ industry projects and 5+ capstone projects in each track, and in-person mentorship and 360° career support. upGrad offers peer-to-peer learning opportunities through access to a global learner base of over 40,000 with whom students can partner on collaborative projects and boost their knowledge. 

Here’s an opportunity to upgrade to lucrative data science roles and attract higher-paying salaries. So, don’t procrastinate – take the upskilling route today.

If you’re looking for career guidance, do reach out to us. We’ll be happy to help!

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Data Science Courses

Explore Free Courses

Suggested Blogs

Top 10 Real-Time SQL Project Ideas: For Beginners &#038; Advanced
15023
Thanks to the big data revolution, the modern business world collects and analyzes millions of bytes of data every day. However, regardless of the bus
Read More

by Pavan Vadapalli

28 Aug 2023

Python Free Online Course with Certification [US 2024]
5519
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Pavan Vadapalli

14 Apr 2023

13 Exciting Data Science Project Ideas &#038; Topics for Beginners in US [2024]
5474
Data Science projects are great for practicing and inheriting new data analysis skills to stay ahead of the competition and gain valuable experience.
Read More

by Rohit Sharma

07 Apr 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
6154
Data refers to the collection of information that is gathered and translated for specific purposes. With over 2.5 quintillion data being produced ever
Read More

by Rohit Sharma

06 Apr 2023

Best Python Free Online Course with Certification You Should Check Out [2024]
5640
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Rohit Sharma

05 Apr 2023

5 Types of Binary Tree in Data Structure Explained
5385
A binary tree is a non-linear tree data structure that contains each node with a maximum of 2 children. The binary name suggests the number 2, so any
Read More

by Rohit Sharma

03 Apr 2023

42 Exciting Python Project Ideas &#038; Topics for Beginners [2024]
5899
Python is an interpreted, high-level, object-oriented programming language and is prominently ranked as one of the top 5 most famous programming langu
Read More

by Rohit Sharma

02 Apr 2023

5 Reasons Why Python Continues To Be The Top Programming Language
5340
Introduction Python is an all-purpose high-end scripting language for programmers, which is easy to understand and replicate. It has a massive base o
Read More

by Rohit Sharma

01 Apr 2023

Why Should One Start Python Coding in Today’s World?
5224
Python is the world’s most popular programming language, used by both professional engineer developers and non-designers. It is a highly demanded lang
Read More

by Rohit Sharma

16 Feb 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon