The if statement in Python is a conditional statement that executes a block of code only when a specific condition is met. It evaluates a boolean expression that returns either True or False, and runs the indented code block when the condition is True. Python's if statements enable decision-making in your programs, allowing different code paths based on varying conditions.
Basic if Statement Syntax
The syntax for an if statement in Python is straightforward:
if condition:
# code to execute if condition is True
statement The condition is a boolean expression (like number > 5 or name == "Alice") that evaluates to either True or False. If the condition evaluates to True, the indented code block executes; if False, Python skips the block entirely.
Example 1: Simple if Statement
number = 10
if number > 0:
print("The number is positive") The number is positive
Example 2: if Statement with False Condition
number = -5
if number > 0:
print("The number is positive")
print("This line always executes") This line always executes
In the second example, since -5 is not greater than 0, the print statement inside the if block is skipped.
Indentation in if Statements
Python relies on indentation (whitespace at the beginning of a line) to define the scope of code blocks, unlike other languages that use curly brackets. All statements inside an if block must be indented by the same amount—typically 4 spaces.
Correct Indentation:
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("You have full legal rights") Incorrect Indentation (will cause an error):
age = 20
if age >= 18:
print("You are an adult") # IndentationError If you don't use proper indentation, Python will raise an IndentationError because it can't determine which statements belong to the if block.
Comparison Operators with if Statements
Python supports standard comparison operators that return boolean values for use in if statements:
==- Equal to!=- Not equal to<- Less than<=- Less than or equal to>- Greater than>=- Greater than or equal to
Example: Using Different Comparison Operators
a = 33
b = 200
if b > a:
print("b is greater than a")
if a != b:
print("a and b are not equal")
if a <= 50:
print("a is 50 or less") b is greater than a a and b are not equal a is 50 or less
Multiple Statements in if Block
You can include multiple statements inside an if block as long as they all have the same level of indentation.
Example:
score = 95
if score >= 90:
print("Excellent work!")
print("You earned an A grade")
grade = "A"
print(f"Your grade is: {grade}") Excellent work! You earned an A grade Your grade is: A
Boolean Variables in if Statements
Boolean variables can be used directly in if statements without comparison operators.
Example:
is_logged_in = True
if is_logged_in:
print("Welcome back!")
is_raining = False
if is_raining:
print("Take an umbrella")
else:
print("Enjoy the sunshine") Welcome back! Enjoy the sunshine
Python treats certain values as False in boolean context: 0, empty strings "", None, and empty collections like [] or . All other values are treated as True.
Truthy and Falsy Values
Python can evaluate many types of values as True or False in conditional statements:
Falsy values (evaluated as False):
0(zero)""(empty string)None[](empty list)(empty dictionary)()(empty tuple)
Truthy values (evaluated as True):
- Any non-zero number (positive or negative)
- Any non-empty string
- Non-empty collections
Example:
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty")
items = [1, 2, 3]
if items:
print("List has items") Name is empty List has items
One-Line if Statement
For simple conditions, you can write an if statement on a single line:
Standard Format:
temperature = 30
if temperature > 25:
print("It's hot outside") Compact Format:
temperature = 30
if temperature > 25: print("It's hot outside") Both versions produce the same output, but the one-line format is more concise for simple statements.
Common Use Cases
Use Case 1: Validating User Input
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote") Use Case 2: Checking Even or Odd Numbers
number = 7
if number % 2 == 0:
print(f"{number} is even") Use Case 3: Password Validation
password = "secret123"
if len(password) >= 8:
print("Password is strong enough") Use Case 4: Checking List Contents
shopping_cart = ["apple", "banana", "milk"]
if "milk" in shopping_cart:
print("Milk is in your cart") Common Mistakes to Avoid
Mistake 1: Forgetting the Colon
# Wrong
if number > 0
print("Positive")
# Correct
if number > 0:
print("Positive") Mistake 2: Using = Instead of ==
x = 5
# Wrong (assignment, not comparison)
if x = 5:
print("x is 5")
# Correct
if x == 5:
print("x is 5") Mistake 3: Inconsistent Indentation
# Wrong
if True:
print("Line 1")
print("Line 2") # Different indentation level
# Correct
if True:
print("Line 1")
print("Line 2") Practice Examples
Example 1: Temperature Checker
temperature = 22
if temperature > 30:
print("It's very hot")
if temperature > 20:
print("It's warm")
if temperature < 10:
print("It's cold") It's warm
Example 2: Grade Assignment
marks = 85
if marks >= 90:
print("Grade: A")
if marks >= 80 and marks < 90:
print("Grade: B")
if marks >= 70 and marks < 80:
print("Grade: C") Grade: B
Example 3: Membership Check
username = "admin"
if username == "admin":
print("Access granted to admin panel")
print("Loading admin dashboard...") Access granted to admin panel Loading admin dashboard...
Try it Yourself
Practice what you've learned by modifying the code below. Try changing the values and conditions to see different outputs!
// Click "Run Code" to see results
Related Topics
Frequently Asked Questions
What is the difference between if and if else in Python?
An if statement only executes code when the condition is True. An if else statement provides an alternative code block that executes when the condition is False.
Do I need to use parentheses around the condition in Python if statements?
No, parentheses are optional in Python. Both if (x > 5): and if x > 5: are valid, but the latter is more Pythonic.
Can I use multiple conditions in a single if statement?
Yes, you can use logical operators like and, or, and not to combine multiple conditions: if age >= 18 and has_license:.
What happens if I don't indent code after an if statement?
Python will raise an IndentationError because it requires indentation to define code blocks.