All about Python if .. else

The if-else statement in Python allows you to execute certain code blocks based on a particular condition. Here’s the general syntax for an if-else statement:

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

Here’s an example of how you could use an if-else statement to determine if a number is even or odd:

num = 4

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

In this example, we use the modulus operator % to determine if the number is even or odd. If the remainder of num / 2 is 0, then the number is even. Otherwise, it is odd.

You can also use multiple if-else statements together to create more complex conditions. Here’s an example of how you could use multiple if-else statements to determine if a number is positive, negative, or zero:

num = -2

if num > 0:
    print(num, "is positive.")
elif num == 0:
    print(num, "is zero.")
else:
    print(num, "is negative.")

In this example, we use the > operator to determine if the number is positive, the == operator to determine if the number is zero, and the < operator to determine if the number is negative.

These are just a few examples of how you can use if-else statements in Python. They are a powerful tool for controlling the flow of your program based on specific conditions. I hope this helps! Let me know if you have any other questions.

Leave a Reply