if-else Statement

Python if-else Statement

Introduction

The if-else statement is a decision-making control structure in Python that allows a program to execute one block of code when a condition is True and another block of code when the condition is False.

In real-world applications, programs often need to make decisions based on different situations. For example:

  • Determining whether a student passed or failed

  • Checking if a user can log in

  • Verifying whether a bank account has sufficient balance

  • Validating test results in automation testing

  • Checking whether a person is eligible to vote

The if-else statement makes these decisions possible by providing two alternative execution paths.

In this tutorial, you will learn about the Python if-else statement, its syntax, examples, practical applications, common mistakes, and best practices.


What is an if-else Statement?

The if-else statement evaluates a condition.

  • If the condition is True, the code inside the if block executes.

  • If the condition is False, the code inside the else block executes.

Only one of the two blocks will run.


Syntax of if-else Statement

if condition:
    statement1
else:
    statement2

Flow of Execution

  1. Python evaluates the condition.

  2. If the condition is True, the if block executes.

  3. If the condition is False, the else block executes.

  4. Only one block is executed.


Simple if-else Example

age = 20

if age >= 18:
    print("Eligible to Vote")
else:
    print("Not Eligible to Vote")

Output

Eligible to Vote

Since the condition is True, the if block executes.


Example with False Condition

age = 15

if age >= 18:
    print("Eligible to Vote")
else:
    print("Not Eligible to Vote")

Output

Not Eligible to Vote

Since the condition is False, the else block executes.


Understanding Indentation

Python uses indentation to define code blocks.

Correct Example

number = 10

if number > 5:
    print("Greater Than 5")
else:
    print("Less Than or Equal to 5")

Incorrect Example

number = 10

if number > 5:
print("Greater Than 5")
else:
print("Less Than or Equal to 5")

Error

IndentationError

Always indent statements inside if and else blocks.


Using Comparison Operators with if-else

Comparison operators are commonly used in conditions.

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Example: Equal To

marks = 50

if marks == 50:
    print("Exactly 50 Marks")
else:
    print("Marks are Different")

Output

Exactly 50 Marks

Example: Not Equal To

marks = 75

if marks != 50:
    print("Marks are Not 50")
else:
    print("Marks are 50")

Output

Marks are Not 50

Example: Greater Than

salary = 60000

if salary > 50000:
    print("High Salary")
else:
    print("Average Salary")

Output

High Salary

Using Logical Operators with if-else

Logical operators help combine multiple conditions.

OperatorMeaning
andBoth conditions must be True
orAt least one condition must be True
notReverses the result

Example: and Operator

age = 25
citizen = True

if age >= 18 and citizen:
    print("Eligible to Vote")
else:
    print("Not Eligible")

Output

Eligible to Vote

Example: or Operator

role = "manager"

if role == "admin" or role == "manager":
    print("Access Granted")
else:
    print("Access Denied")

Output

Access Granted

Example: not Operator

is_blocked = False

if not is_blocked:
    print("Access Allowed")
else:
    print("Access Denied")

Output

Access Allowed

Using if-else with Strings

language = "Python"

if language == "Python":
    print("Python Selected")
else:
    print("Other Language Selected")

Output

Python Selected

Using if-else with Numbers

number = 25

if number % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")

Output

Odd Number

Using if-else with Boolean Values

is_logged_in = True

if is_logged_in:
    print("Welcome User")
else:
    print("Please Login")

Output

Welcome User

Using User Input with if-else

age = int(input("Enter your age: "))

if age >= 18:
    print("Eligible to Vote")
else:
    print("Not Eligible to Vote")

Sample Input

17

Output

Not Eligible to Vote

Multiple Statements Inside if and else

salary = 70000

if salary >= 50000:
    print("Employee Eligible")
    print("Bonus Approved")
    print("Email Notification Sent")
else:
    print("Employee Not Eligible")
    print("Bonus Rejected")

Output

Employee Eligible
Bonus Approved
Email Notification Sent

Nested if-else Statement

An if-else statement can contain another if-else statement.

age = 22

if age >= 18:
    if age >= 21:
        print("Eligible for Adult Membership")
    else:
        print("Eligible for Youth Membership")
else:
    print("Not Eligible")

Output

Eligible for Adult Membership

Real-World Example: Exam Result

marks = 65

if marks >= 35:
    print("Pass")
else:
    print("Fail")

Output

Pass

Real-World Example: ATM Withdrawal

balance = 10000
withdraw_amount = 5000

if withdraw_amount <= balance:
    print("Withdrawal Successful")
else:
    print("Insufficient Balance")

Output

Withdrawal Successful

Real-World Example: Login Validation

username = "admin"

if username == "admin":
    print("Login Successful")
else:
    print("Invalid Username")

Output

Login Successful

Real-World Example: Age Verification

age = 16

if age >= 18:
    print("Adult")
else:
    print("Minor")

Output

Minor

if-else Statement in Automation Testing

The if-else statement is frequently used in Selenium, API Testing, and Test Automation frameworks.


Example: API Response Validation

status_code = 200

if status_code == 200:
    print("API Test Passed")
else:
    print("API Test Failed")

Output

API Test Passed

Example: Element Validation

element_found = True

if element_found:
    print("Element Present")
else:
    print("Element Missing")

Output

Element Present

Example: Title Validation

actual_title = "Dashboard"
expected_title = "Dashboard"

if actual_title == expected_title:
    print("Test Passed")
else:
    print("Test Failed")

Output

Test Passed

Truthy and Falsy Values

Python automatically treats certain values as True or False.

Truthy Values

True
1
"Python"
[1, 2, 3]

Falsy Values

False
0
""
[]
None

Example

name = ""

if name:
    print("Name Available")
else:
    print("Name Not Available")

Output

Name Not Available

Common Mistakes Beginners Make

Using = Instead of ==

Incorrect

age = 18

if age = 18:
    print("Eligible")
else:
    print("Not Eligible")

Error

SyntaxError

Correct

if age == 18:
    print("Eligible")
else:
    print("Not Eligible")

Forgetting the Colon (:)

Incorrect

if age >= 18
    print("Eligible")
else
    print("Not Eligible")

Error

SyntaxError

Correct

if age >= 18:
    print("Eligible")
else:
    print("Not Eligible")

Incorrect Indentation

Incorrect

if age >= 18:
print("Eligible")
else:
print("Not Eligible")

Error

IndentationError

Correct

if age >= 18:
    print("Eligible")
else:
    print("Not Eligible")

Best Practices

Use Meaningful Conditions

if user_age >= 18:

Instead of:

if x >= 18:

Keep Conditions Simple

Simple conditions improve readability.


Use Boolean Variables

if is_logged_in:

Instead of:

if is_logged_in == True:

Maintain Proper Indentation

Consistent indentation makes code easier to understand.


Advantages of if-else Statement

  • Enables decision-making in programs

  • Controls program flow effectively

  • Handles both True and False conditions

  • Supports business logic implementation

  • Essential for automation testing and application development


Difference Between if and if-else

Featureif Statementif-else Statement
Condition TrueExecutes codeExecutes if block
Condition FalseSkips codeExecutes else block
Number of Execution PathsOneTwo
Decision MakingBasicComplete

Conclusion

The Python if-else statement is a fundamental control structure used to make decisions in programs. It allows different code blocks to execute depending on whether a condition evaluates to True or False.

From user authentication and banking applications to automation testing and API validation, the if-else statement is one of the most commonly used programming constructs.

Mastering if-else statements is essential for writing dynamic, intelligent, and real-world Python applications.


Frequently Asked Questions (FAQs)

What is an if-else statement in Python?

An if-else statement executes one block of code when a condition is True and another block when the condition is False.

Example:

age = 20

if age >= 18:
    print("Eligible")
else:
    print("Not Eligible")

Can I use multiple statements inside if and else?

Yes.

if True:
    print("Line 1")
    print("Line 2")
else:
    print("Line 3")

Can I use logical operators with if-else?

Yes.

age = 25
citizen = True

if age >= 18 and citizen:
    print("Eligible")
else:
    print("Not Eligible")

Why is indentation important?

Indentation tells Python which statements belong to the if block and which belong to the else block.


Can if-else statements be nested?

Yes. An if-else statement can be placed inside another if or else block.


Key Takeaways

  • The if-else statement provides two execution paths.

  • The if block runs when the condition is True.

  • The else block runs when the condition is False.

  • Comparison and logical operators are commonly used in conditions.

  • Proper indentation is mandatory in Python.

  • if-else statements work with numbers, strings, Booleans, and user input.

  • They are heavily used in automation testing, validation, authentication, and business logic.

  • Understanding if-else statements is essential for writing real-world Python programs.