Python if-else Statement

Introduction to the Python if-else Statement

The if-else statement is a fundamental control structure in Python that allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program.

Syntax of the Python if-else Statement

The syntax of the if-else statement in Python is as follows:

if condition:
    # code block executed if the condition is true
else:
    # code block executed if the condition is false

The condition is an expression that evaluates to either True or False. If the condition is True, the code block under the if statement is executed. Otherwise, the code block under the else statement is executed.

Examples of the Python if-else Statement

Let’s look at some examples to understand how the if-else statement works in Python.

Example 1: Checking if a Number is Positive or Negative

num = -5

if num >= 0:
    print("The number is positive or zero.")
else:
    print("The number is negative.")

In this example, we use the if-else statement to check if the value of the variable num is greater than or equal to zero. If it is, we print a message stating that the number is positive or zero. Otherwise, we print a message stating that the number is negative.

If you run this code, it will output:

The number is negative.

Example 2: Checking if a Number is Even or Odd

num = 7

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

In this example, we use the if-else statement to check if the remainder of dividing the value of the variable num by 2 is equal to 0. If it is, we print a message stating that the number is even. Otherwise, we print a message stating that the number is odd.

If you run this code, it will output:

The number is odd.

Example 3: Checking if a Year is a Leap Year

year = 2024

if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print("The year is a leap year.")
else:
    print("The year is not a leap year.")

In this example, we use the if-else statement to check if the value of the variable year is a leap year. We check if the year is divisible by 4, but not divisible by 100 unless it is also divisible by 400. If the condition is true, we print a message stating that the year is a leap year. Otherwise, we print a message stating that the year is not a leap year.

If you run this code, it will output:

The year is a leap year.

Conclusion

The if-else statement is a powerful tool in Python that allows you to make decisions and control the flow of your program. It helps you execute different blocks of code based on certain conditions. By understanding the syntax and examples provided in this article, you should now have a good grasp of how to use the if-else statement in your Python programs.

Scroll to Top