Python: if…else [Flow Control]

if Condition

if True:
    print("This is true")
    
if False:
    print("This is false") # Never printed
Python

Output:

This is true
Plaintext

For example, check the following example-

x = 80

if x >= 40:
    print("Success")
Python

Output:

Success
Plaintext

if…else

x = 80

if x >= 40:
    print("Success")
else: 
    print("Failure")
Python

Output:

Success
Plaintext

if…elif…else

x = 80

if x > 100:
    print("Wrong value")
elif x > 80:
    print("Excellent score")
elif x >= 40:
    print("Good score")
else: 
    print("Fail")
Python

Output:

Good score
Plaintext

Nested if…else

x = 80

if x > 40:
    print("X is greater than 40")
    
    if x >= 80:
        if x == 100:
            print("Perfect Score")
        elif x >= 90:
            print('Excellent score')
        else:
            print("Good score")
    else:
        print("Average score")
        
Python

Output:

X is greater than 40
Good score
Plaintext

Example #1: Discount Calculation

discount_threshold = 500
discount_percentage = 0.25

super_discount_threshold = 2000
super_discount_percentage = 0.4

product_price = float(input("Enter product price: "))

# Check if price satisfies minimum price threshold
# and calculate discount
if product_price >= super_discount_threshold:
    discount = product_price * super_discount_percentage
elif product_price >= discount_threshold:
    discount = product_price * discount_percentage
else:
    discount = 0

price_after_discount = product_price - discount

print(f"Product price after discount: {price_after_discount}")
print(f"Discount amount: {discount}")
Python

Output:

Run the script and enter price “100”-

Enter product price: 100
Product price after discount: 100.0
Discount amount: 0
Plaintext

Rerun the script and enter price “999”-

Enter product price: 999
Product price after discount: 749.25
Discount amount: 249.75
Plaintext

Rerun the script and enter price “5000”-

Enter product price: 5000
Product price after discount: 3000.0
Discount amount: 2000.0
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.