Table of contents
1.
Introduction
2.
If Statement
2.1.
Example of If Statement
2.2.
Python
3.
if-else Statement
3.1.
Example of an if-else Statement
3.2.
Python
3.3.
Example: Simple if-else
3.4.
Python
3.5.
Example: if-else with List Comprehension
3.6.
Example: if-else with Functions
3.7.
Python
4.
Flowchart of Python if-else Statement
5.
Using Python if-else Statement
5.1.
Python
6.
Python if-else Statement in a List Comprehension
7.
Types of Control Flow in Python
8.
Nested If-Else
8.1.
Example: Nested if-else
8.2.
Python
9.
Frequently Asked Questions
9.1.
Is the else part mandatory in an if-else statement?
9.2.
What is the Elif statement in Python?
9.3.
What is the use of if-else in Python?
9.4.
How to do two if conditions in Python?
10.
Conclusion
Last Updated: Jan 13, 2025
Easy

Python If Else Statements-Conditional Statements

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In programming, decision-making is an essential skill, and conditional statements are the tools that make it possible. Python, known for its simplicity and readability, provides powerful constructs to handle these decisions: the if, else, and elif statements. These conditional statements allow your code to react dynamically to different scenarios, making it smarter and more efficient.

Python If Else Statements – Conditional Statements

If Statement

The if statement in Python is used to execute a block of code only if a specified condition evaluates to True. It acts as the foundation of decision-making in Python, allowing your program to make choices based on given conditions.

The basic syntax of an if statement is as follows:

if condition:
    # Block of code to execute if the condition is True

Here:

  • condition: This is an expression that evaluates to either True or False.
  • Block of code: This is the indented code that runs only when the condition is True. If the condition is False, this block is skipped.

Example of If Statement

Let’s look at a simple example where we check if a number is positive:

  • Python

Python

# Example of an if statement
number = 10

if number > 0:
print("The number is positive.")
You can also try this code with Online Python Compiler
Run Code

 

Output:

The number is positive.

if-else Statement

if-else statement in Python helps your program decide what to do based on whether a condition is true or false. It's like a simple question your code asks: "Is this condition true? If yes, do this; if no, do that."

Here's how it works:

  • If: This part checks the condition you're interested in. If the condition is true, the code inside the if block runs.
     
  • Else: This part is optional. It's what happens if the condition checked by the if part isn't true. The code inside the else block runs instead.

Example of an if-else Statement

Let's look at a basic example. Imagine you have a variable named score that holds a number. You want to print "Pass" if the score is 50 or more and "Fail" if it's less than 50.

  • Python

Python

score = 70

if score >= 50:

   print("Pass")

else:

   print("Fail")
You can also try this code with Online Python Compiler
Run Code

Output

Pass


In this example, since the score is 70, which is more than 50, the program prints "Pass". If we change the score to 40, it would print "Fail".

Example: Simple if-else

  • Python

Python

temperature = 30

if temperature > 25:

   print("It's a hot day.")

else:

   print("It's not a hot day.")
You can also try this code with Online Python Compiler
Run Code

 

Output

It's not a hot day.


In this example, the program checks if the temperature is above 25 degrees. If it is, it prints "It's a hot day." Otherwise, it prints "It's not a hot day."

Example: if-else with List Comprehension

ages = [22, 15, 32, 18, 25]
status = ["adult" if age >= 18 else "minor" for age in ages]


Here, we have a list of ages and we want to label each person as an "adult" or "minor." The list comprehension with an if-else statement makes this easy. For each age in the list, it checks if that age is 18 or older. If so, "adult" gets added to the new list; if not, "minor" does.

Example: if-else with Functions

You can also use if-else statements inside functions to make them more dynamic, allowing them to perform different actions based on the inputs they receive.

  • Python

Python

def check_age(age):

   if age >= 18:

       return "You're an adult."

   else:

       return "You're a minor."

print(check_age(20)) 

print(check_age(16)) 
You can also try this code with Online Python Compiler
Run Code

Output: 

You're an adult.
You're a minor.

In this function named check_age, the program takes an age as input and checks if it's 18 or older. If it is, the function returns "You're an adult." If not, it returns "You're a minor." This example shows how if-else statements can make functions more flexible and useful in different situations.

Flowchart of Python if-else Statement

For the Python if-else statement, a flowchart helps us see how the decision-making works. It's like a map that guides you through the "if this, then do that; else, do something else" process.

Flowchart of Python if-else Statement

Here’s what the basic flowchart for an if-else statement looks like:

  • Start: This is where your decision-making begins.
     
  • Condition: Here, you check a condition. It's a yes-or-no question.
     
  • If Yes (True): If the condition is true, you follow the "yes" path and execute the block of code under 'if'.
     
  • If No (False): If the condition is false, you follow the "no" path and execute the block of code under 'else'.
     
  • End: This is where your decision-making ends, and the program moves on.

Using Python if-else Statement

Using the if-else statement in Python is about making your code do different things based on conditions. It's a straightforward way to give instructions: "If this condition is true, do this; otherwise, do that."

Here's a step-by-step guide to using if-else in your code:

  • Write the if statement and include the condition you want to check right after it. Conditions are questions that can be answered with "yes" (true) or "no" (false).
     
  • Add your code block under the if statement. This is what runs if the condition is true. Start this block with an indentation to tell Python it's part of the if statement.
     
  • Write the else statement if there's something you want to happen when the if condition is not true. Else doesn't need a condition; it's the "otherwise" part of your instruction.
     
  • Add your code block under the else statement, also indented, for what you want to do when the condition is false.
     

Here's a simple example:

  • Python

Python

age = 18

if age >= 18:

   print("You can vote.")

else:

   print("You're too young to vote.")
You can also try this code with Online Python Compiler
Run Code


Output

You can vote.


In this example, the program checks if the age is 18 or more. If true, it prints "You can vote." If not, it says, "You're too young to vote." This way, the if-else statement helps your program make decisions and take different actions based on conditions.

Python if-else Statement in a List Comprehension

List comprehensions in Python are a short and concise way to create lists. When you add an if-else statement inside a list comprehension, it lets you create more complex lists easily.

Here's how you can use an if-else statement in a list comprehension:

  • Start with the basic structure of a list comprehension, which is [expression for item in iterable].
     
  • Add the if-else statement inside the expression part. It will decide what each item in the new list should be based on a condition.
     

For example, let's say you have a list of numbers and you want to create a new list where each number is labeled as "even" or "odd" based on its value:

numbers = [1, 2, 3, 4, 5]
labels = ["even" if number % 2 == 0 else "odd" for number in numbers]


In this example, number % 2 == 0 is the condition that checks if a number is even. If it's true, "even" gets added to the new list. If it's false, "odd" gets added instead. This way, the if-else statement inside the list comprehension helps you build more dynamic lists based on conditions.

Types of Control Flow in Python

In Python, control flow is about deciding which lines of code to run based on certain conditions, similar to making choices in everyday life. There are a few different ways to control the flow of your program, but let's focus on the main types that involve making decisions: if-else statements, for loops, and while loops.

  • If-else Statements: These are the most straightforward way to make decisions in your code. If a specific condition is true, your program does one thing; if not, it does something else.
     
  • For Loops: For loops are used when you want to repeat a block of code a certain number of times or for each item in a list or another collection. It's like saying, "For each day in a week, do this."
     
  • While Loops: While loops keep running as long as a certain condition is true. It's like saying, "While it's raining, keep the umbrella open."

Nested If-Else

A nested if-else statement is an if-else block inside another if-else block. It allows you to create multiple levels of decision-making in your program. This structure is useful when you need to evaluate multiple conditions in a hierarchical manner.

The syntax for a nested if-else statement is:

if condition1:
    # Block of code if condition1 is True
    if condition2:
        # Block of code if condition2 is True
    else:
        # Block of code if condition2 is False
else:
    # Block of code if condition1 is False

Example: Nested if-else

Sometimes, you might need to check multiple conditions one inside the other. This is where nested if-else statements come in handy.

  • Python

Python

score = 75

if score >= 90:

   print("Grade: A")

elif score >= 75:

   print("Grade: B")

else:

   print("Grade: C or below")
You can also try this code with Online Python Compiler
Run Code

Output

Grade: B


In this example, the program first checks if the score is 90 or above. If it is, it prints "Grade: A". If not, it moves to the next condition: is the score 75 or above? Since the score is 75, it prints "Grade: B". If neither condition is met, it would print "Grade: C or below".

Frequently Asked Questions

Is the else part mandatory in an if-else statement?

No, the else part is not mandatory. You can use an if statement on its own if you only need to execute code when a certain condition is true. The else part is only needed if you want to do something specific when the if condition is not met.

What is the Elif statement in Python?

The elif statement in Python allows you to check multiple conditions sequentially, executing the corresponding block when the first True condition is found.

What is the use of if-else in Python?

The if-else statement in Python executes one block of code if a condition is True and another block if the condition is False.

How to do two if conditions in Python?

To check two if conditions, you can use logical operators (and, or) or write separate if statements for independent checks.

Conclusion

In this article, we've learned the basics & beyond of Python's if-else statements. Starting with what they are & how they work, we looked into the types of control flow in Python, focusing on if-else statements. We visualized their flow with flowcharts, discussed how to use them effectively, and saw their application in list comprehensions. At the end we implemented our learning with different examples in various scenarios.

Live masterclass