Python if Statement



Python if statement performs conditional execution. It contains a logical expression using which data is compared and a decision is made based on the result of the comparison.

if Statement Syntax

if expression:
   statement(s)

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

if Statement Flow Diagram (Flowchart)

Python if statement

Example of Python if Statement

Let us consider an example of a customer entitiled 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

In Python, we first set a discount variable to 0 and accept the amount as input from user.

Then comes the conditional statement if amount > 1000. Put : symbol that starts conditional block wherein discount applicable is calculated. Obviously, discount or not, next statement by default prints amount-discount. If applied, it will be subtracted, if not it is 0.

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