Python - if Statement



Python If Statement

The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based on the result of the comparison.

Syntax of the if Statement

if expression:
   # statement(s) to be executed

If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if block is executed.

Flow Diagram (Flowchart) of the if Statement

The below diagram shows flowchart of the if statement −

Python if statement

Example of Python if Statement

Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process −

If Statement Flowchart

First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount.

Python code for the above flowchart can be written as follows −

discount = 0
amount = 1200

# Check he amount value
if amount > 1000:
   discount = amount * 10 / 100

print("amount = ", amount - discount)

Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output

amount = 1080.0

Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −

amount = 800
Advertisements