Python : If Else

In Python, the `if` statement is used for conditional execution of code based on the evaluation of an expression. The `if` statement can be extended with `elif` (short for "else if") and `else` clauses to handle multiple conditions. Here's how they work:

Basic `if` statement:


x = 10

if x > 5:
    print("x is greater than 5")

 

if`-else statement:


x = 10

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

 

if - elif - else statement:


x = 10

if x > 15:
    print("x is greater than 15")
elif x > 10:
    print("x is greater than 10 but not greater than 15")
else:
    print("x is 10 or less")

 

Nested if statements:



x = 10

if x > 5:
    print("x is greater than 5")
    if x > 15:
        print("x is also greater than 15")
    else:
        print("x is not greater than 15")
else:
    print("x is not greater than 5")

 

Ternary conditional expression (inline `if`-`else`):


You can also use a ternary conditional expression for simple `if`-`else` scenarios in a single line.


x = 10
message = "x is greater than 5" if x > 5 else "x is not greater than 5"
print(message)

 

Multiple conditions in `if` statements:


You can use logical operators `and`, `or`, and `not` to combine multiple conditions in `if` statements.


x = 10

if x > 5 and x < 15:
    print("x is between 5 and 15")
elif x < 5 or x > 15:
    print("x is outside the range 5 to 15")

 

Truthy and Falsy values:

 

In Python, values such as empty lists (`[ ]`), empty strings (`" "`), zero (`0`), and `None` are considered falsy, while all other values are truthy.


x = [ ]

if x:
    print("x is not empty")
else:
    print("x is empty")

This covers the basics of using `if`, `elif`, and `else` statements in Python. They are fundamental tools for controlling the flow of your program based on different conditions.