If else Statements

Learning Python if-else statement using simple examples

Python’s if-else statements are a cornerstone of control flow, allowing you to execute code based on conditions. Here’s a step-by-step tutorial to help you understand how to use if-else statements in Python.

Step 1: Basic Syntax

The basic syntax of an if statement is:

Python
if condition:
    # code to execute if condition is True

To add more conditions, you can use elif (short for “else if”) and else:

Python
if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition1 is False but condition2 is True
else:
    # code to execute if both conditions are False

Step 2: Simple Example

Here’s a basic example that checks if a number is greater than 10:

Python
x = 15

if x > 10:
    print("x is greater than 10.")

Output:

x is greater than 10.

Step 3: Using elif and else

You can add more conditions using elif and else:

Python
x = 10

if x > 10:
    print("x is greater than 10.")
elif x == 10:
    print("x is equal to 10.")
else:
    print("x is less than 10.")

Output:

x is equal to 10.

Step 4: Logical Operators

You can use logical operators like and, or, and not to create more complex conditions.

Python
x = 15

if x > 10 and x < 20:
    print("x is between 10 and 20.")

Output:

x is between 10 and 20.

Step 5: Nested if Statements

You can also nest if statements within other if statements:

Python
x = 25

if x > 10:
    print("x is greater than 10.")

    if x > 20:
        print("In fact, x is also greater than 20.")

Output:

x is greater than 10.
In fact, x is also greater than 20.

Step 6: Using pass

The pass statement is a placeholder when you don’t want to execute any code.

Python
x = 5

if x > 10:
    pass

Here, nothing will be executed because x > 10 is False and pass does nothing.

Step 7: Using Ternary Operator

Python has a ternary operator for simple if-else conditions:

Python
x = 15
message = "Greater than 10" if x > 10 else "Not greater than 10"
print(message)

Output:

Greater than 10

Step 8: if With Lists

You can use if to check if an item is in a list:

Python
my_list = [1, 2, 3, 4]

if 3 in my_list:
    print("3 is in the list.")

Output:

3 is in the list.

Step 9: Checking Multiple Conditions with all and any

The all() and any() functions can be used to check multiple conditions:

Python
conditions = [True, True, False]

if all(conditions):
    print("All conditions are true.")
elif any(conditions):
    print("At least one condition is true.")

Output:

At least one condition is true.

I hope this step-by-step tutorial gives you a solid understanding of if-else statements in Python. Feel free to experiment with different conditions and nesting structures to deepen your knowledge.