View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Python-if-else-statement

Updated on 16/04/20255,041 Views

The Python if-else statement is a fundamental control structure that enables your programs to make decisions based on conditions. It forms the backbone of logical reasoning within your code, allowing programs to execute different blocks of code depending on whether specified conditions are true or false.

In real-world applications, these conditional statements help create dynamic, responsive software that can adapt to different scenarios from simple user input validation to complex business logic implementation.

# Simple example of if-else in action
user_age = 18
if user_age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")

Output

You are eligible to vote.

This  guide will take you through everything you need to know about if-else statements in Python, from basic syntax to advanced implementations with a real-world example.

Advance your Python skills with a globally recognized MS in Data Science from LJMU and IIITB

What is the Python If-Else Statement?

The if-else statement in Python is a conditional statement that executes a block of code when a specified condition evaluates to True and a different block when the condition is False.

Basic Syntax

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

The key components of an if-else statement are:

  1. The if keyword, followed by a condition that evaluates to either True or False
  2. A colon (:) after the condition
  3. An indented block of code to execute if the condition is True
  4. The else keyword followed by a colon (:)

An indented block of code to execute if the condition is False

Transform your Python knowledge into data-driven insights with Upgrad’s online Data Science course.

Examples of Python If-Else Statements

Let's explore some practical examples to understand how if-else statements work in Python:

Example 1: Number Comparison

Problem Statement: Imagine a student learning mathematics needs a program to check if a number is even or odd to help with understanding number properties.

# Program to check if a number is even or odd
number = int(input("Enter a number: "))

# Check if number is divisible by 2
if number % 2 == 0:
    print(f"{number} is an even number.")
else:
    print(f"{number} is an odd number.")

Output:

Enter a number: 7
7 is an odd number.

This example demonstrates a basic if-else statement for mathematical categorization which is a common task in programming.

Curious about Python developer salaries in 2025? Discover the latest trends now

Example 2: Password Validation

Problem Statement: A login system needs to verify if a user's password meets the minimum length requirement before allowing access to the system.

# Simple password length checker
password = input("Enter your password: ")

# Check if password meets minimum length requirement
if len(password) >= 8:
    print("Password accepted.")
    print("Login successful!")
else:
    print("Password too short!")
    print("Your password must be at least 8 characters long.")

Output:

Enter your password: pass123
Password too short!
Your password must be at least 8 characters long.

This example shows how if-else statements are used for input validation which is a critical component of secure applications.

Example 3: Grade Classification

Problem Statement: A teacher needs to automate the process of assigning letter grades based on numerical scores to save time when evaluating student exams.

# Program to determine pass/fail status and grade
marks = float(input("Enter your marks (out of 100): "))

# Determine if student has passed or failed
if marks >= 40:
    print("Congratulations! You have passed the exam.")
    
    # Additional message based on performance level
    if marks >= 90:
        print("You received an A grade. Excellent performance!")
    elif marks >= 80:
        print("You received a B grade. Very good performance!")
    elif marks >= 70:
        print("You received a C grade. Good performance!")
    elif marks >= 60:
        print("You received a D grade. Satisfactory performance!")
    else:
        print("You received an E grade. Work harder next time!")
else:
    print("Sorry, you have failed the exam.")
    print("Please contact your teacher for remedial classes.")

Output:

Enter your marks (out of 100): 75
Congratulations! You have passed the exam.
You received a C grade. Good performance!

This example demonstrates how multiple if-else statements can be combined to create a comprehensive grading system.Real-World Application of If-Else Statement in Python

Let's explore a comprehensive real-world example that demonstrates the power of if-else statements in a practical application.

E-commerce Shopping Cart Discount Calculator

Problem Statement: An Indian e-commerce website wants to implement a discount system for its shopping cart that calculates discounts based on the total purchase amount and customer loyalty status.

# E-commerce shopping cart discount calculator
cart_total = float(input("Enter cart total (in Rs.): "))
is_registered_user = input("Are you a registered user? (yes/no): ").lower() == "yes"
has_promo_code = input("Do you have a promo code? (yes/no): ").lower() == "yes"

# Initialize discount variables
discount_percentage = 0
discount_amount = 0
final_amount = cart_total
discount_reason = ""

# Apply discount logic based on cart total
if cart_total >= 5000:
    discount_percentage = 10
    discount_reason = "Purchase above Rs. 5,000"
else:
    if cart_total >= 3000:
        discount_percentage = 7.5
        discount_reason = "Purchase above Rs. 3,000"
    else:
        if cart_total >= 1000:
            discount_percentage = 5
            discount_reason = "Purchase above Rs. 1,000"
        else:
            discount_reason = "No minimum purchase discount applicable"

# Apply additional discount for registered users
if is_registered_user:
    if discount_percentage > 0:
        discount_percentage += 2  # Additional 2% for registered users
        discount_reason += " + 2% registered user bonus"
    else:
        discount_percentage = 2
        discount_reason = "2% registered user discount"

# Apply promo code discount if applicable
if has_promo_code:
    if cart_total >= 2000:
        # Fixed amount discount for promo code
        promo_discount = 200
        discount_reason += f" + Rs. 200 promo code discount"
    else:
        print("Sorry, promo code requires minimum purchase of Rs. 2,000")

# Calculate final amounts
discount_amount = (cart_total * discount_percentage / 100)
if has_promo_code and cart_total >= 2000:
    discount_amount += promo_discount

final_amount = cart_total - discount_amount

# Display cart summary
print("\n===== SHOPPING CART SUMMARY =====")
print(f"Cart Total: Rs. {cart_total:.2f}")
print(f"Discount: Rs. {discount_amount:.2f} ({discount_reason})")
print(f"Final Amount: Rs. {final_amount:.2f}")

# Display additional offers or suggestions
if final_amount >= 4000:
    print("\nYou qualify for free shipping!")
else:
    shipping_cost = 99
    print(f"\nShipping charge of Rs. {shipping_cost} will be applied.")
    amount_for_free_shipping = 4000 - final_amount
    if amount_for_free_shipping > 0:
        print(f"Add items worth Rs. {amount_for_free_shipping:.2f} more to qualify for free shipping!")

Output:

Enter cart total (in Rs.): 3500
Are you a registered user? (yes/no): yes
Do you have a promo code? (yes/no): yes

===== SHOPPING CART SUMMARY =====

Cart Total: Rs. 3500.00

Discount: Rs. 462.50 (Purchase above Rs. 3,000 + 2% registered user bonus + Rs. 200 promo code discount)

Final Amount: Rs. 3037.50

Shipping charge of Rs. 99 will be applied.

Add items worth Rs. 962.50 more to qualify for free shipping!

This e-commerce example demonstrates how if-else statements are used to implement business logic for calculating discounts, applying promotional offers, and providing personalized recommendations to customers.

Conclusion and Best Practices

The if-else statement is a very important part of logical decision-making in Python programming. By mastering this fundamental control structure, you gain the ability to create amazing programs that can adapt to different situations and user inputs.

Best Practices for Using If-Else Statements

  1. Keep conditions simple and readable
  2. Use meaningful variable names
  3. Be consistent with indentation
  4. Consider the default case
  5. Test all branches

FAQ Section

1. Can I use an if statement without an else clause?

Yes, the else clause is optional. If you only need to execute code when a condition is true and do nothing otherwise, you can use an if statement by itself.

2. What values are considered False in Python conditions?

In Python, the following values are considered False:

  • False
  • None
  • Zero of any numeric type (0, 0.0)
  • Empty sequences ('', [], ())
  • Empty mappings ({})
  • Objects that implement __bool__() or __len__() that return 0 or False

3. Can I compare multiple values in a single condition?

Yes, you can use logical operators (and, or, not) to combine multiple conditions:

if age >= 18 and income > 25000:

    print("Eligible for credit card")

4. Is there a limit to how many if-else statements I can nest?

While there's no technical limit, deeply nested if-else statements can make code difficult to read and maintain. If you find yourself nesting beyond 3-4 levels, consider refactoring your code.

5. Can I write an if-else statement in a single line?

Yes, Python offers a ternary operator for concise if-else expressions:

status = "Adult" if age >= 18 else "Minor"

6. How are if-else statements different from switch/case in other languages?

Python doesn't have a built-in switch/case statement like many other languages. Multiple if-elif-else statements typically serve this purpose, though Python 3.10+ introduced the match-case statement as an alternative.

7. Do I need to use parentheses around conditions in if statements?

No, parentheses are not required around conditions in Python if statements, though they can be used for clarity or when combining multiple conditions:

# Both of these are valid:
if x > 5:
    print("x is greater than 5")
    
if (x > 5 and y < 10):
    print("x is greater than 5 and y is less than 10")

8. How do I check if a value is within a range?

You can use comparison operators with and or use Python's chained comparisons:

# Both are equivalent:
if 0 <= x <= 100:
    print("x is between 0 and 100")
    
if x >= 0 and x <= 100:
    print("x is between 0 and 100")

9. What's the difference between == and is in if conditions?

== checks if two values are equal, while is checks if two variables refer to the same object in memory. For most primitive types, use == for comparison:

if x == 10:  # Checks if value is equal to 10
    print("x equals 10")
    
if x is None:  # Checking for None is a common use case for 'is'
    print("x is None")

10. How do I handle "if not" conditions elegantly?

Use the not operator to negate conditions, but consider rewriting for clarity when possible:

# Instead of:
if not is_valid:
    print("Invalid input")
    
# Consider if the opposite makes more sense:
if is_valid:
    print("Processing valid input")
else:
    print("Invalid input")

11. Can I have multiple conditions that lead to the same action?

Yes, you can use the or operator to combine conditions:

if age < 18 or income < 10000:
    print("Not eligible for loan")
image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.