Python Control Flow Statements (if-elif-else)

Python if, elif, and else statements are used to control the flow of your code based on certain conditions. If the condition is true, the code inside the if statement is executed, and if the condition is false, the code inside the if statement is skipped.

The basic syntax of an if statement in Python is as follows:

if condition:
    # code to be executed if the condition is true

The condition is a boolean expression that evaluates to either True or False. If the condition is True, the code inside the if statement is executed. If the condition is False, the code inside the if statement is skipped.

Here’s an example:

x = 5

if x > 0:
    print("x is positive")

In this example, the condition is “x > 0”, which is True because x is 5. Therefore, the code inside the if statement is executed, and “x is positive” is printed to the console.

You can also use else statements to provide code to be executed if the condition is false. Here’s an example:

x = -5

if x > 0:
    print("x is positive")
else:
    print("x is not positive")

In this example, the condition is “x > 0”, which is False because x is -5. Therefore, the code inside the else statement is executed, and “x is not positive” is printed to the console.

You can also use elif statements (short for “else if”) to provide additional conditions to check if the first condition is False. Here’s an example:

x = 0

if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")

In this example, the condition “x > 0” is False, so the condition “x < 0” is checked. This condition is also False because x is 0, so the code inside the else statement is executed, and “x is zero” is printed to the console.

Note:

Remember that indentation is very important in Python. The code inside the if statement (or any other control flow statement) should be indented to show that it is part of the if statement. The standard indentation is 4 spaces.