Python If … Else

Python If … Else statement is used to check the condition and execute the block of code based on the outcome of the condition. The If … Else statement is also known as the decision-making statement, which is used to make decisions based on a certain condition.

The basic syntax for the If … Else statement in Python is as follows:

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

In the above syntax, if the condition is true, the block of code under the if statement will be executed. If the condition is false, the block of code under the else statement will be executed.

Example:

# Program to check if a number is positive or negative

num = float(input("Enter a number: "))

if num > 0:
    print("The number is positive")
else:
    print("The number is negative")

In the above example, we take input from the user and check whether the input number is positive or negative. If the number is greater than 0, the program will print “The number is positive” else it will print “The number is negative”.

Let’s see another example:

# Program to check if a number is even or odd

num = int(input("Enter a number: "))

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

In the above example, we take an input from the user and check whether the input number is even or odd. If the number is divisible by 2, the program will print “The number is even” else it will print “The number is odd”.

In conclusion, If … Else statement is a powerful tool in Python to make decisions based on a certain condition. It allows the programmer to execute a block of code based on the outcome of the condition. The syntax is simple and easy to use, and it is one of the essential concepts in Python programming.