Python IF-Else

The 'if-else' concepts.

IF Else

In Python, if, if-else, and nested 'if-else' statements are used for conditional branching in your code. Here's how they work:

1. if statement:

[syntax]

if condition:
    # code block to execute if the condition is true

[code]

py Copy Code
x = 10
if x > 0:
    print("x is positive")

It allows you to execute a block of code only if a certain condition is true.


2. if-else statement:

[syntax]

if condition:
    # code block to execute if the condition is true
else:
    # code block to execute if the condition is false

[code]

py Copy Code
x = 10
if x % 2 == 0:
    print("x is even")
else:
    print("x is odd")

It allows you to execute one block of code if the condition is true and another block of code if the condition is false.


3. nested if-else statement:

[syntax]

if condition1:
    # code block to execute if condition1 is true
    if condition2:
        # code block to execute if both condition1 and condition2 are true
    else:
        # code block to execute if condition1 is true but condition2 is false
else:
    # code block to execute if condition1 is false

[code]

py Copy Code
x = 10
if x > 0:
    if x % 2 == 0:
        print("x is a positive even number")
    else:
        print("x is a positive odd number")
else:
    print("x is not a positive number")

It's when you have an if-else statement inside another if-else statement. This allows for more complex conditional logic.


Here's a simple example to illustrate these concepts:

PDF Copy Code
# Python: Concepts of if-else statements
x = 10

# Example of if statement
if x > 0:
    print("x is positive")

# Example of if-else statement
if x % 2 == 0:
    print("x is even")
else:
    print("x is odd")

# Example of nested if-else statement
if x > 0:
    if x % 2 == 0:
        print("x is a positive even number")
    else:
        print("x is a positive odd number")
else:
    print("x is not a positive number")
Output:
x is positive
x is even
x is a positive even number

* In this example, the program checks whether 'x' is positive, whether it's even or odd, and whether it's a positive even or odd number, using if, if-else, and nested if-else statements.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.