Conditional Statements in Python

Conditional statements are fundamental to programming, allowing you to execute specific blocks of code based on certain conditions. In Python, these statements enable the program to make decisions and perform different actions depending on the provided conditions.

Types of Conditional Statements:

Code Examples of Conditional Statements:

If Statement Syntax:

if condition:
            # Code to execute if condition is true

Code Example

# If Statement
        age = 18
        if age >= 18:
            print("You are an adult.")

Output

You are an adult.

If-Else Statement Syntax:

if condition:
            # Code to execute if condition is true
        else:
            # Code to execute if condition is false

Code Example

# If-Else Statement
        marks = 75
        if marks >= 60:
            print("You passed the exam.")
        else:
            print("You failed the exam.")

Output

You passed the exam.

Nested If Statement Syntax:

if condition1:
            if condition2:
                # Code to execute if condition1 and condition2 are true

Code Example

# Nested If Statement
        num = 10
        if num > 0:
            if num % 2 == 0:
                print("Positive even number.")
            else:
                print("Positive odd number.")

Output

Positive even number.

If-Elif-Else Statement Syntax:

if condition1:
            # Code to execute if condition1 is true
        elif condition2:
            # Code to execute if condition1 is false and condition2 is true
        else:
            # Code to execute if both conditions are false

Code Example

# If-Elif-Else Statement
        day = 3
        if day == 1:
            print("Monday")
        elif day == 2:
            print("Tuesday")
        elif day == 3:
            print("Wednesday")
        else:
            print("Other day")

Output

Wednesday

Important Points on Conditional Statements:

Conclusion

Mastering conditional statements is essential for creating dynamic and responsive programs in Python. Understanding how to structure and nest conditions effectively allows for more complex decision-making processes in your code.