CodeSutraHub

if Statement in Python

Python provides three types of decision (conditional) statements. Let us first learn about the if statement.

if Statement in Python

In an if statement, the statements are executed only when the given condition evaluates to True.

Syntax:
if condition:
    statements
In the above syntax, the condition is a Boolean expression. If the condition evaluates to True, the statements inside the if block are executed. If the condition evaluates to False, the statements inside the if block are not executed.

Algorithm to Calculate Discount


Step 1: Start
Step 2: Read purchase amount
Step 3: discount = 0
Step 4: If purchase >= 1000
            discount = (10 * purchase) / 100
Step 5: Print discount
Step 6: Stop

Flowchart

discount flowchart

Example of if Statement in Python


# Example of if statement
purchase = 1500
discount = 0

if purchase >= 1000:
    discount = (10 * purchase) / 100

print("Discount =", discount)
Output:
Discount = 150.0
  • purchase = 1500:
    The variable purchase is created and assigned the value 1500.
  • discount = 0:
    The variable discount is initialized with 0.
  • if purchase >= 1000:
    The condition is checked and evaluates to True. Therefore, the statement inside the if block is executed and a 10% discount is calculated. If purchase = 500, the condition would be False, and the discount would remain 0.
  • print("Discount =", discount):
    Finally, the discount value is printed.

Conditional Expression (Shorthand if) in Python

In Python, a conditional expression (also known as shorthand if) can be used to write an if-else statement in a single line.

Syntax:

value_if_true if condition else value_if_false

If the condition is True, value_if_true is returned. If the condition is False, value_if_false is returned.

# Example of conditional expression
marks = 85
result = "Pass" if marks >= 35 else "Fail"
print("Result:", result)

What We Have Learned So Far

  • Learned about the if statement
  • Wrote and understood a program using the if statement
  • Python if-else will be covered in the next topic

Below Video Explains if Statement in Python