Saturday, February 9, 2019

If .. Else in Python

The if statement:

In python, the if statement is used for decision making. The if statement checks for a condition and executes a bunch of instructions if the condition is true.

if a > 5:
    print("Hello World!")

The above code will print Hello World! if the value of a is greater than 5, otherwise nothing will be printed.

The if - else statement:

An else block can also be used with the if statement. In this form, the if statement checks for a condition and if the condition is true, it executes the statements contained in the if block. And if the condition is false, the statements in the else block get executed.

if a>5:
    print("Greater than 5")
else:
    print("Less than or equal to 5")

The above code will print Greater than 5 if the value of a is greater than 5, otherwise it will print Less than or equal to 5.

The if - elif - else statement:

In some cases, we need to test another condition if the condition of if evaluates to false. In such cases we use elif. We can use as many elif blocks as we need, before we finally pass the control to the else block. The following example demonstrates this.

if marks >= 60:
    print("First Division")
elif marks >= 45:
    print("Second Division")
elif marks >= 30:
    print("Third Division")
else:
    print("Failed")

.

No comments: