Python If-else

The if-else statement in Python is a conditional control structure that allows you to execute different blocks of code based on whether a specified condition is true or false. It is a fundamental component of programming that helps you make decisions in your code. The general syntax of an if-else statement in Python is as follows:

if condition:
    # code to be executed if the condition is True
else:
    # code to be executed if the condition is False
Python

Here's a step-by-step explanation of how the if-else statement works in Python:

1. The if keyword marks the beginning of the if-else statement, followed by a condition. This condition should be a boolean expression (an expression that evaluates to either True or False).

2. If the condition is True, the code block indented under the if statement is executed. If the condition is False, the code block indented under the else statement is executed.

3. You can have any number of statements inside the if and else blocks, but they must be indented consistently (usually with four spaces or a tab character).

4. It's important to note that the else part is optional. You can use just an if statement if you only want to execute code when a condition is True.

# Example 1: Simple if-else statement
age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are not yet an adult.")
Python

In this example, the condition age >= 18 is checked. If the condition is true (which it is in this case because age is 18), it will execute the code block under the if statement, printing "You are an adult." If the condition is false, it will execute the code block under the else statement, printing "You are not yet an adult."

# Example 2: Using if-else to determine if a number is positive, negative, or zero
number = -5

if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")
Python

In this example, we use the if, elif (short for "else if"), and else keywords to check whether the variable number is positive, negative, or zero. Depending on the value of number, the corresponding code block will be executed.

The if-else statement is an essential tool for controlling the flow of your Python program based on various conditions, making your code more dynamic and capable of handling different scenarios.