Python conditions

In Python, an if-else condition allows the program to make decisions based on whether a certain condition is True or False. It determines which block of code to execute depending on the evaluation of a condition.

Syntax:


if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Explanation:

if condition: If the condition is True, the block of code inside the if the statement is executed.

else: If the if condition is False, the block of code inside the else the statement is executed.

Example:


age = 21

if age >= 21:
    print("You are Adult.")
else:
    print("You are not Adult.")

In this example:

If the age is 21 or more, the output will be "You are Adult."

Otherwise, the output will be "You are not Adult."

elif (else if) for Multiple Conditions:

You can also use elif to check multiple conditions:


x = 20

if x > 20:
    print("x is greater than 20")
elif x == 20:
    print("x is exactly 20")
else:
    print("x is less than 20")

Nested if statements:

You can also nest if statements within each other:


x = 20
y = 30

if x > 10:
    if y > 15:
        print("x is greater than 10 and y is greater than 15")

Short-hand if (Ternary Operator):


x = 10
print("x is greater than 5") if x > 5 else print("x is 5 or less")