Python if Statements Explained (Python Docs 4.1) | if, elif, else & Beginner Guide
This page explains the official Python if statements documentation (Python Docs 4.1) in simple language. Learn how Python's if, elif, and else statements work, use comparison and logical operators, write nested conditions, avoid common mistakes, and understand real-world decision making with beginner-friendly explanations and practical examples. By the end of this guide, you'll know how Python evaluates conditions, when to use if, elif, and else, combine multiple conditions with logical operators, write clean decision-making code, and avoid the most common beginner mistakes.
Basic if Statement Syntax
An if statement checks a condition. If it's True, the indented block runs. If it's False, Python skips it entirely.
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
# If you enter 42, the output is:
# More
There can be zero or more elif parts, and the else part is optional. The keyword elif is short for "else if", and is useful to avoid excessive indentation. An if โฆ elif โฆ elif โฆ sequence is a substitute for the switch or case statements found in other languages.
elif and else โ Handling Multiple Conditions
Python checks conditions from top to bottom and stops at the first one that's True. The else block is the fallback โ it runs only if every condition above it was False.
score = 74
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
# Output: Grade: C
# Python stops as soon as score >= 60 is True โ it doesn't check further
True one. If you put a broader condition before a narrower one (like score >= 60 before score >= 90), the narrower one will never run โ it'll already be caught by the broader check.
if without elif or else
Both elif and else are optional. A standalone if is perfectly valid when you only need to act on one condition:
name = "Palak"
# No elif, no else โ just a simple guard
if name == "Palak":
print("Welcome back, Palak!")
# This still works fine โ if the condition is False, nothing happens
Comparison Operators in if Statements
The condition inside an if statement is any expression that evaluates to True or False. These are the operators you'll use most:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 0 |
> | Greater than | x > 10 |
< | Less than | x < 10 |
>= | Greater than or equal to | x >= 18 |
<= | Less than or equal to | x <= 100 |
in | Value exists in a sequence | "a" in "Palak" |
not in | Value not in a sequence | x not in [1, 2, 3] |
is | Same object in memory | x is None |
is not | Not the same object | x is not None |
== to compare values, use is to check identity. x == None works but x is None is the correct Python idiom โ None is a singleton, so identity comparison is more accurate and faster.
Combining Conditions with and, or, not
You can combine multiple conditions in one if using logical operators:
age = 20
city = "Delhi"
# and โ both conditions must be True
if age >= 18 and city == "Delhi":
print("Eligible Delhi voter")
# or โ at least one condition must be True
if age < 13 or age > 60:
print("Special pricing applies")
# not โ flips True to False and vice versa
logged_in = False
if not logged_in:
print("Please log in first")
# Chaining comparisons โ Python allows this naturally
marks = 75
if 60 <= marks < 80:
print("B grade") # True โ marks is between 60 and 80
Nested if Statements
You can put an if inside another if. Python uses indentation to know which block belongs to which condition โ so get the spacing right.
score = 85
attended = True
if score >= 50:
if attended:
print("Passed โ attendance confirmed")
else:
print("Score ok, but attendance too low")
else:
print("Failed")
and/or, early returns, or helper functions.
Real-World Examples of Python if Statements
You'll use if statements in almost every Python project. Here are some common real-world examples:
- Login systems: Allow users to log in only if the username and password are correct.
- ATM software: Check whether the account has enough balance before allowing a withdrawal.
- Games: Decide whether the player wins, loses, or unlocks the next level.
- E-commerce websites: Apply discounts only if the cart value exceeds a certain amount.
- Weather apps: Recommend carrying an umbrella if rain is expected.
Common if Statement Mistakes
if x = 5: raises a SyntaxError. Single = is assignment; double == is comparison. This is one of the most common beginner errors across every programming language.
if x > 0 without a colon raises a SyntaxError. Every if, elif, and else line must end with :.
Python uses indentation to define blocks โ not curly braces. If your code inside the if isn't indented consistently (4 spaces is standard), you'll get an IndentationError.
If you check score >= 50 before score >= 90, a score of 95 will match the first condition and never reach the second. Always order from most specific to most general.
if is_active == True: is redundant. Just write if is_active:. Similarly, if is_active == False: should be if not is_active:. Cleaner and more Pythonic.
Python if Statement Interview Questions and Answers
These come up in Python beginner and junior-level interviews โ straightforward but easy to fumble if you haven't thought them through:
if starts a new conditional check โ Python always evaluates it. elif only runs if every if and elif above it was False. You can have as many elif blocks as you need, but only one if to start the chain. Think of elif as "otherwise, if this other thing is true."== compares values โ it checks whether two objects have the same content. is checks identity โ whether two variables point to the exact same object in memory. a = [1, 2]; b = [1, 2]; a == b is True, but a is b is False because they're two separate list objects. Use is only for None, True, and False โ for everything else, use ==.if block can have only one else โ it's the final fallback. If you need multiple branches, use elif for the middle cases and else for the last one. Having two else blocks on the same if raises a SyntaxError.False. 0 < x < 10 is equivalent to (0 < x) and (x < 10), but Python only evaluates x once. This is a Python-specific feature โ in languages like C or Java, 0 < x < 10 would not work the same way.if age >= 18 and city == "Delhi": is a single condition โ both must be true together. A nested if lets you handle each condition separately with its own block. Use logical operators when both conditions lead to the same outcome. Use nested if when the inner condition only makes sense to check after the outer one passes, or when each combination needs different handling.False in an if condition: None, False, 0, 0.0, empty string "", empty list [], empty dict {}, empty tuple (), and empty set set(). Everything else is truthy. This means if my_list: is a clean way to check if a list has any items โ no need to write if len(my_list) > 0:.Python if Statement FAQ
if statement checks a condition and runs a block of code only if that condition is True. It's Python's primary tool for branching โ making decisions about which code to run based on data.elif (short for "else if") checks another condition if the previous if was False. You can have as many elif blocks as you need. else has no condition โ it's the fallback that runs only if every if and elif above it was False.elif and else are optional. A standalone if is valid. If the condition is False and there's no else, Python simply moves on to the next line after the block.elif is short for "else if". From the Python docs: it's useful to avoid excessive indentation. Without elif, you'd have to nest if statements inside else blocks, which gets messy fast. An if/elif/elif chain is Python's equivalent of switch/case in other languages.value = "yes" if condition else "no". This is useful for simple assignments. For anything more complex โ multiple statements, no else โ use the standard multi-line form for readability.For Loop ยท While Loop ยท Lists ยท Dictionaries ยท List Comprehension . Sets . Tuples . Lists as Stack and Queue ยท Nested List Comprehension ยท User Input ยท