Python if Statement
Introduction
The if statement is one of the most important decision-making statements in Python. It allows a program to execute specific code only when a particular condition is true.
In real-world applications, decisions are made constantly. For example:
Checking whether a user is eligible to vote
Validating login credentials
Determining whether a test case passed or failed
Checking account balances before transactions
Validating API responses
The Python if statement makes these decisions possible by evaluating conditions and executing code accordingly.
In this tutorial, you will learn about the Python if statement, its syntax, examples, real-world applications, common mistakes, and best practices.
What is an if Statement?
An if statement is used to execute a block of code only when a specified condition evaluates to True.
If the condition evaluates to False, the code block is skipped.
Syntax of if Statement
if condition:
statement
Flow
Python evaluates the condition.
If the condition is
True, the code inside theifblock executes.If the condition is
False, the block is skipped.
Simple if Statement Example
age = 20
if age >= 18:
print("Eligible to Vote")
Output
Eligible to Vote
Since the condition age >= 18 is True, Python executes the print statement.
Example with False Condition
age = 15
if age >= 18:
print("Eligible to Vote")
Output
No Output
The condition is False, so the code block is skipped.
Understanding Indentation
Python uses indentation to define blocks of code.
Correct Example
age = 20
if age >= 18:
print("Eligible to Vote")
Incorrect Example
age = 20
if age >= 18:
print("Eligible to Vote")
Error
IndentationError
The code inside the if block must be indented.
Using Comparison Operators in if Statements
Comparison operators are commonly used with if.
| Operator | Meaning |
|---|---|
| == | 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("Marks are 50")
Output
Marks are 50
Example: Not Equal To
marks = 75
if marks != 50:
print("Marks are not 50")
Output
Marks are not 50
Example: Greater Than
salary = 60000
if salary > 50000:
print("High Salary")
Output
High Salary
Using Logical Operators in if Statements
Logical operators combine multiple conditions.
| Operator | Meaning |
|---|---|
| and | Both conditions must be True |
| or | At least one condition must be True |
| not | Reverses the result |
Example: and Operator
age = 25
citizen = True
if age >= 18 and citizen:
print("Eligible to Vote")
Output
Eligible to Vote
Example: or Operator
role = "admin"
if role == "admin" or role == "manager":
print("Access Granted")
Output
Access Granted
Example: not Operator
is_blocked = False
if not is_blocked:
print("Access Allowed")
Output
Access Allowed
Using if with Strings
name = "Python"
if name == "Python":
print("Programming Language Found")
Output
Programming Language Found
Using if with Numbers
number = 100
if number > 50:
print("Number is Greater Than 50")
Output
Number is Greater Than 50
Using if with Boolean Values
is_logged_in = True
if is_logged_in:
print("Welcome User")
Output
Welcome User
Using User Input with if Statement
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to Vote")
Sample Input
20
Output
Eligible to Vote
Multiple Statements Inside if Block
salary = 50000
if salary >= 50000:
print("Employee Eligible")
print("Bonus Approved")
print("Notification Sent")
Output
Employee Eligible
Bonus Approved
Notification Sent
All indented statements execute when the condition is True.
Nested if Statement
An if statement can contain another if statement.
age = 25
if age >= 18:
if age >= 21:
print("Eligible for Adult Membership")
Output
Eligible for Adult Membership
Real-World Example: ATM Withdrawal
balance = 10000
withdraw_amount = 5000
if withdraw_amount <= balance:
print("Withdrawal Successful")
Output
Withdrawal Successful
Real-World Example: Login Validation
username = "admin"
if username == "admin":
print("Login Successful")
Output
Login Successful
Real-World Example: Exam Result
marks = 75
if marks >= 35:
print("Pass")
Output
Pass
if Statement in Automation Testing
The if statement is extensively used in Selenium, API Testing, and Automation Frameworks.
Example: Status Code Validation
status_code = 200
if status_code == 200:
print("API Test Passed")
Output
API Test Passed
Example: Element Validation
element_found = True
if element_found:
print("Element Present")
Output
Element Present
Example: Test Result Validation
actual_title = "Dashboard"
expected_title = "Dashboard"
if actual_title == expected_title:
print("Test Passed")
Output
Test Passed
Truthy and Falsy Values
Python treats certain values as True or False automatically.
Truthy Values
True
1
"Python"
[1, 2]
Falsy Values
False
0
""
[]
None
Example
name = "John"
if name:
print("Name Available")
Output
Name Available
Example
name = ""
if name:
print("Name Available")
Output
No Output
Empty strings evaluate to False.
Common Mistakes Beginners Make
Using = Instead of ==
Incorrect
age = 18
if age = 18:
print("Eligible")
Error
SyntaxError
Correct
if age == 18:
print("Eligible")
Forgetting Colon (:)
Incorrect
if age >= 18
print("Eligible")
Error
SyntaxError
Correct
if age >= 18:
print("Eligible")
Incorrect Indentation
Incorrect
if age >= 18:
print("Eligible")
Error
IndentationError
Correct
if age >= 18:
print("Eligible")
Best Practices
Use Meaningful Conditions
if user_age >= 18:
Instead of:
if x >= 18:
Keep Conditions Simple
Avoid overly complex conditions whenever possible.
Use Boolean Variables
if is_logged_in:
Instead of:
if is_logged_in == True:
Properly Indent Code Blocks
Consistent indentation improves readability.
Advantages of if Statement
Enables decision-making in programs
Controls program flow
Makes applications dynamic
Supports real-world business logic
Essential for automation testing and software development
Conclusion
The Python if statement is a fundamental control structure that allows programs to make decisions based on conditions. It evaluates a condition and executes code only when that condition is True.
Whether you are building web applications, automation frameworks, APIs, desktop applications, or simple scripts, the if statement is one of the most frequently used programming constructs.
Understanding and mastering the if statement is essential for writing intelligent and dynamic Python programs.
Frequently Asked Questions (FAQs)
What is an if statement in Python?
An if statement executes a block of code when a specified condition is True.
Example:
age = 20
if age >= 18:
print("Eligible")
What happens when the condition is False?
Python skips the if block and continues with the rest of the program.
Why is indentation important in an if statement?
Indentation tells Python which statements belong to the if block.
Can an if statement contain multiple statements?
Yes.
Example:
if True:
print("Line 1")
print("Line 2")
Can I use logical operators inside an if statement?
Yes.
Example:
age = 20
citizen = True
if age >= 18 and citizen:
print("Eligible")
Key Takeaways
The
ifstatement is used for decision-making.Code executes only when the condition evaluates to True.
Python uses indentation to define
ifblocks.Comparison operators are commonly used with
if.Logical operators can combine multiple conditions.
ifstatements work with numbers, strings, Booleans, and user input.They are widely used in automation testing, validation, authentication, and business logic.
Mastering
ifstatements is essential for Python programming.
