If else logic in python

The if and else statements are fundamental control structures in Python. They allow you to execute certain blocks of code based on specific conditions. In this tutorial, we’ll explore how to use them effectively.

What Is an if Statement?

The if statement evaluates a condition, and if the condition is True, it executes the block of code indented beneath it. Here's an example:

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

Output:

x is greater than 5

Adding an else Statement

An else statement provides an alternative block of code to execute when the condition in the if statement is False:

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

Output:

x is not greater than 5

Using elif for Multiple Conditions

The elif (short for "else if") statement lets you check multiple conditions:

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

Output:

x is greater than 5 but not greater than 10

Nesting if Statements

You can nest if statements to check more complex conditions:

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

Output:

x is greater than 5 and y is greater than 10

Logical Operators in Conditions

Use logical operators like and, or, and not to combine conditions:

x = 7
y = 12
if x > 5 and y > 10:
    print("Both conditions are True")

Output:

Both conditions are True

Next Steps

Practice writing your own if, elif, and else statements with various conditions. Understanding control flow is essential for solving problems in Python. Happy coding! To learn more check out loops in python!