Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“ Python if-else Statement: Complete Guide

Python if-else Statement - Complete Guide

The if-else statement gives your program the power to choose between two paths.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is the if-else Statement?
  • Syntax of if-else Statement
  • Flowchart of if-else Statement
  • Simple Example
  • Even or Odd Example
  • Multiple Conditions
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What the if-else statement is — two-way decision making
  • Syntax of if-else — how to write conditional statements
  • Flowchart of if-else — visualizing the flow
  • Simple examples — comparing numbers
  • Even or Odd — classic example
  • Multiple conditions — combining with logical operators
  • Common mistakes — and how to avoid them

What is the if-else Statement?

The if-else statement takes decision making to the next level. While the if statement only executes code when a condition is true, the if-else statement provides two paths — one for when the condition is true, and another for when it's false.

šŸ’” Key insight: Think of if-else as a fork in the road. You choose one path if the condition is true, and the other path if it's false. There's no going back — every condition has a path.

The if-else statement adds an additional step in the decision-making process compared to the basic if statement. The starting of the if-else statement is similar to the basic if statement, but it includes an else block that handles the false condition.

Syntax of if-else Statement

# Syntax of if-else Statement
if condition:
    # Execute this block if condition is true
    # Statements for true condition
else:
    # Execute this block if condition is false
    # Statements for false condition

# Example
age = 16
if age >= 18:
    print("You can vote!")
else:
    print("You cannot vote yet!")

# Output: You cannot vote yet!

šŸ“– Breaking it down: Python evaluates the condition. If it's True, the if block executes and the else block is skipped. If it's False, the if block is skipped and the else block executes. Either way, exactly one block runs.

āš ļø Important: The else block is optional but powerful. It ensures that every condition has a response, making your program more robust and user-friendly.

Flowchart of if-else Statement

Let's visualize how the if-else statement works using a flowchart:

Flowchart:

    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │    START    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │   Condition │ ◄─── Test the condition
    │   (True?)   │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           │
      True │   False
           ā–¼     ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │  Execute    │  │  Execute    │
    │  Body of if │  │  Body of    │
    │  (True)     │  │  else (False)│
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           │                │
           ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                    ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │   END       │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

What happens:
1. The flow enters the if-else statement
2. The condition is tested
3. If True → body of if executes
4. If False → body of else executes
5. Program continues with the next statement after if-else

Simple Example

Let's compare two numbers using if-else:

# Find the smaller of two numbers using if-else
p = 8
q = 6

if p < q:   # Test condition
    print(p, "is smaller than", q)
else:       # When condition is false
    print(q, "is smaller than", p)

# Output:
# 6 is smaller than 8

šŸ“– Explanation: In this example, we used a single if-else statement. The condition p < q evaluates to False (8 is not less than 6), so the if block is skipped and the else block executes, displaying 6 is smaller than 8. This is cleaner than using two separate if statements.

Even or Odd Example

Here's the classic example using if-else:

# Python script to find if a number is even or odd using if-else
x = int(input("Enter Any Number: "))

if x % 2 == 0:
    print(x, "is Even")
else:
    print(x, "is Odd")

# Output:
# Enter Any Number: 5
# 5 is Odd

šŸ“– Explanation:
1. x = int(input("Enter Any Number: ")) — accepts user input and converts it to an integer.
2. if x % 2 == 0: — checks if the remainder when divided by 2 is 0. If true, the number is even.
3. else: — if the condition is false, the number is odd.
4. Since 5 % 2 = 1, the condition is false, so the else block executes and displays 5 is Odd.

Multiple Conditions

You can combine multiple conditions using logical operators — and, or, and not:

# Multiple conditions with if-else
age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")
else:
    print("You cannot drive!")

# Another example with or
is_weekend = True
is_holiday = False

if is_weekend or is_holiday:
    print("You can relax!")
else:
    print("It's a workday!")

# Output:
# You can drive!
# You can relax!

Common Mistakes to Avoid

āŒ Mistake 1: Using = instead of ==

# WRONG (assignment instead of comparison)
if x = 5:  # This will cause a SyntaxError!
    print("x is 5")
else:
    print("x is not 5")

# CORRECT (comparison)
if x == 5:
    print("x is 5")
else:
    print("x is not 5")

āŒ Mistake 2: Missing Colon

# WRONG
if x > 0  # Missing colon!
    print("Positive")
else
    print("Negative")

# CORRECT
if x > 0:
    print("Positive")
else:
    print("Negative")

āŒ Mistake 3: Incorrect Indentation

# WRONG (inconsistent indentation)
if x > 0:
print("Positive")  # IndentationError!
else:
    print("Negative")

# CORRECT (consistent indentation)
if x > 0:
    print("Positive")
else:
    print("Negative")

Try It Yourself!

Experiment with the if-else statement directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
IF-ELSE STATEMENT
========================================

1. COMPARE TWO NUMBERS
6 is smaller than 8

2. EVEN OR ODD
7 is Odd

3. VOTING ELIGIBILITY
You cannot vote yet!

4. MULTIPLE CONDITIONS
You can drive!

āœ… Explore different if-else conditions!
šŸ†

šŸŽ‰ You've Mastered Python if-else Statement!

You understand the if-else statement, syntax, flow, and how to handle two-way decision making. This is essential for building robust programs!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about the if-else statement:

1. What does the else block do in an if-else statement?
2. What is the correct syntax for an if-else statement?
3. In if x > 0: print("Positive") else: print("Negative"), what prints if x = -5?
4. What is the result of if 5 > 3: print("A") else: print("B")?
5. Is the else block mandatory in an if-else statement?

Frequently Asked Questions

šŸ¤” What is the difference between if and if-else? ā–¼

if only executes code when the condition is true. if-else provides two paths — one for true and one for false. if-else ensures every condition has a response.

šŸ”§ Can I have multiple statements in if and else blocks? ā–¼

Yes! Both if and else blocks can contain multiple statements. Just make sure they're all indented at the same level.

šŸ“ Can I nest if-else statements? ā–¼

Yes! You can put an if-else inside another if or else block. This is called nesting. However, deep nesting can make code hard to read.

šŸ“Š Can I use logical operators in if-else conditions? ā–¼

Yes! You can combine conditions using and, or, and not. For example: if age >= 18 and has_license:.

⚔ What happens if I forget the else block? ā–¼

If you forget the else block, it becomes a simple if statement. Nothing executes when the condition is false. This is valid syntax and sometimes intentional.

šŸŽÆ Which is better: two if statements or one if-else? ā–¼

Use if-else when you have two mutually exclusive paths. Use two if statements when the conditions are independent and both could be true.

šŸ“š Where to Go From Here

Now that you've mastered the if-else statement, here are the next topics to explore:

šŸ“ The if-elif-else Ladder

Handle multiple conditions with the if-elif-else ladder.

Learn More →

šŸ“ Nested if Statements

Master complex decision making with nested if statements.

Learn More →

šŸ“ Shorthand if-else

Learn the ternary operator for concise conditional expressions.

Learn More →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: if Statement Next: if-elif-else Ladder →