Programs

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. 

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. 

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.

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.

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!

Plan Your Data Science Career Today

0 replies on “Python If-Else Condition Explained [With Examples]”

Accelerate Your Career with upGrad

Our Best Data Science Courses

×