Python if-else

In Python, the if-else statement allows you to execute different blocks of code based on a condition. The basic syntax for if-else in Python is as follows:

Example
if condition:
    # code block to execute if the condition is true
else:
    # code block to execute if the condition is false

Here's an example that demonstrates the usage of if-else in Python:

Example
# Example 1
x = 10

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

# Output: x is greater than 5


# Example 2
age = 18

if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")

# Output: You are eligible to vote

In the first example, the condition x > 5 is evaluated. If the condition is true, the code block inside the if statement is executed. Otherwise, the code block inside the else statement is executed.

In the second example, the condition age >= 18 is checked. If the condition is true (i.e., the age is 18 or greater), the code block inside the if statement is executed. Otherwise, the code block inside the else statement is executed.

The if-else statement provides a way to handle different scenarios based on conditions, allowing your program to make decisions and take appropriate actions accordingly.