Skip to content

Python If Else Elif

if else

In Python, if-else statements are used for conditional execution of code. These statements allow your program to make decisions based on whether a certain condition is true or false.

Example:

        
# Example of if-else statement
age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
        
    

In the example above, the if statement checks if the variable age is greater than or equal to 18. If the condition is true, the code inside the if block is executed; otherwise, the code inside the else block is executed.

if..elif..else

In Python, the elif statement is short for "else if." It is used in conjunction with the if statement to test multiple conditions sequentially. When the if condition is not met, the program evaluates the elif condition, and if it is true, the corresponding block of code is executed.

Example:

        
# Example using if, elif, and else
age = 25

if age < 18:
    print("You are a minor.")
elif 18 <= age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")
        
    

In the example above, the program checks the age of an individual. If the age is less than 18, it prints "You are a minor." If the age is between 18 and 65 (inclusive), it prints "You are an adult." Otherwise, if none of the previous conditions are met, it prints "You are a senior citizen."