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 Statement: Complete Guide

Python if Statement - Complete Guide

The if statement is the simplest and most powerful decision-making tool in Python.

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 Statement?
  • Syntax of if Statement
  • Flowchart of if Statement
  • Simple Condition 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 statement is — the simplest decision-making tool
  • Syntax of if — how to write conditional statements
  • Indentation rules — why indentation matters in Python
  • Simple conditions — using relational operators
  • Multiple conditions — using and, or, not
  • Real-world examples — even/odd, number comparison
  • Common mistakes — and how to avoid them

What is the if Statement?

The if statement is the simplest and most important decision-making tool in Python. It allows you to execute a block of code only when a certain condition is true. Think of it as a gatekeeper — it checks a condition and decides whether to let the code pass through or skip it.

šŸ’” Key insight: The if statement is the foundation of all conditional logic in Python. Every other decision-making statement builds upon it. Master the if statement, and you've mastered the core of Python's control flow.

A programmer may have to make different choices. These choices execute different Python statements or parts of a script depending on certain conditions. The if statement is used for the conditional execution of statements. It decides whether a certain statement or block of statements will be executed or not — if a given condition is true, then the statements or block of statements is executed; otherwise, it's skipped.

Syntax of if Statement

# Syntax of if Statement
if condition:
    # Body of if
    # Python statements to execute if condition is true

# Example
age = 18
if age >= 18:
    print("You are eligible to vote!")

# Output: You are eligible to vote!

šŸ“– Breaking it down: The if keyword is followed by a condition (an expression that evaluates to True or False). The condition is followed by a colon (:). The body of the if statement is indented (usually 4 spaces). Python evaluates the condition. If it's True, the indented code runs. If it's False, the indented code is skipped.

āš ļø Important: Python uses indentation to define blocks of code. All statements in the body of an if must be indented at the same level. This is different from many other languages that use curly braces {}.

Flowchart of if Statement

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

Flowchart:

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

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

Simple Condition Example

Let's look at a simple example that checks which number is smaller:

# Find the smaller of two numbers
p = 8
q = 6

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

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

# Output:
# 6 is smaller than 8

šŸ“– Explanation: In this example, we used two separate if statements. The first condition p < q evaluates to False (8 is not less than 6), so its body is skipped. The second condition q < p evaluates to True (6 is less than 8), so its body executes and displays the output.

Even or Odd Example

This is a classic example that checks if a number is even or odd using the modulus operator:

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

if n % 2 == 0:
    print(n, "is Even")

if n % 2 == 1:
    print(n, "is Odd")

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

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

Multiple Conditions

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

# Using 'and' operator
age = 25
has_license = True

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

# Using 'or' operator
is_weekend = True
is_holiday = False

if is_weekend or is_holiday:
    print("You can relax!")

# Using 'not' operator
is_raining = False

if not is_raining:
    print("Go outside and enjoy!")

# Output:
# You can drive!
# You can relax!
# Go outside and enjoy!

šŸ’” Remember: When using multiple conditions, parentheses can make your code clearer: if (age >= 18) and (has_license):.

Common Mistakes to Avoid

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

This is the most common mistake in conditional statements!

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

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

āŒ Mistake 2: Missing Colon

Every if statement needs a colon at the end.

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

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

āŒ Mistake 3: Incorrect Indentation

Python relies on indentation to define code blocks. Inconsistent indentation causes errors.

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

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

Try It Yourself!

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

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

1. SIMPLE IF
You can vote!

2. EVEN OR ODD
7 is odd

3. MULTIPLE CONDITIONS
10 is between 0 and 20

4. USER INPUT

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

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

You understand the if statement, syntax, indentation, and how to use conditions. This is the foundation of all decision-making in Python!

Quick Quiz – Test Your Knowledge

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

1. What is the correct syntax for an if statement?
2. What happens if the condition in an if statement is False?
3. What is the result of if 5 > 3: print("True")?
4. Which operator is used for comparison in an if statement?
5. What does the and operator do in a condition?

Frequently Asked Questions

šŸ¤” What is the difference between = and ==? ā–¼

= is the assignment operator used to assign values to variables. == is the equality operator used to compare two values. Using = in a condition causes a SyntaxError.

šŸ”§ Does Python require indentation in if statements? ā–¼

Yes! Python uses indentation to define code blocks. All statements in the body of an if must be indented at the same level (usually 4 spaces). Inconsistent indentation causes errors.

šŸ“ Can I have multiple if statements? ā–¼

Yes! You can use multiple if statements to check different conditions independently. Each if is evaluated separately, and multiple blocks can execute if their conditions are true.

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

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

⚔ What happens if the condition is True? ā–¼

If the condition is True, the indented block of code inside the if statement executes. After that, the program continues with the next statement after the if block.

šŸŽÆ Can I put another if inside an if? ā–¼

Yes! This is called a nested if. The inner if only runs if the outer if condition is true. However, deep nesting can make code hard to read, so use it sparingly.

šŸ“š Where to Go From Here

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

šŸ“ The if-else Statement

Learn how to handle two-way decision making with if-else.

Learn More →

šŸ“ 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 →
šŸ“– 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: Decision Making Next: if-else Statement →