CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

PYTHON - If Statement

Python - if Statement

Python If Statement

Theif statementinPythonevaluates 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

PYTHON CODE
if expression:
   # statement(s) to be executed

If the boolean expression evaluates to TRUE, then the statement(s) inside theif blockis 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 βˆ’

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 βˆ’

First, set adiscountvariable to 0 and anamountvariable to 1200. Then, use anif statementto 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 βˆ’

PYTHON CODE
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 followingoutputβˆ’

PYTHON CODE
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 βˆ’

PYTHON CODE
amount = 800