Python

Important Statements

The if Statement

Executes a block of code only if a condition is true.

if condition:
    # Code to execute if condition is True
    statement_1
    statement_2
    # ...

The elif Statement

(Short for "else if") Checks another condition if the preceding if or elif conditions were false. You can have multiple elif blocks.

if first_condition:
    # Code for first_condition
    pass # or other statements
elif second_condition:
    # Code to execute if first_condition is False AND second_condition is True
    statement_a
    statement_b
    # ...
# You can add more elif blocks here

The else Statement

Executes a block of code if all preceding if and elif conditions were false. There can only be one else block, and it must be the last one in the chain.

if condition_1:
    # Code for condition_1
    pass
elif condition_2:
    # Code for condition_2
    pass
else:
    # Code to execute if condition_1 is False AND condition_2 is False
    final_statement_x
    final_statement_y
    # ...

Combining if, elif, and else

You can combine these statements to create complex conditional logic.

temperature = 25

if temperature > 30:
    print("It's hot!")
elif temperature > 20:
    print("It's warm.")
else:
    print("It's cool.")