Python's if statement tests any expression for truthiness — not just booleans — so an if can directly test a number, string, or collection without an explicit comparison, since 0, empty strings, and empty collections are all falsy. Unlike many languages, Python has no braces or parentheses around the condition; instead, indentation itself defines which statements belong to the block, making consistent indentation a syntactic requirement, not just a style choice.
1Understanding if Statement
Python's if statement tests any expression for truthiness — not just booleans — so an if can directly test a number, string, or collection without an explicit comparison, since 0, empty strings, and empty collections are all falsy. Unlike many languages, Python has no braces or parentheses around the condition; instead, indentation itself defines which statements belong to the block, making consistent indentation a syntactic requirement, not just a style choice.
Test truthiness directly, e.g. `if items:`, instead of comparing to an empty value explicitly, e.g. checking that its length is greater than zero — it's more idiomatic and works uniformly across strings, lists, dicts, and other falsy-aware types.
age = 20
if age >= 18:
print("You can vote")2Practical Example
Here is a real-world application of if Statement showing how it is used in production Python code.
user_input = []
if user_input:
print("Processing input")
else:
print("No input provided")3Best Practices
Follow these guidelines when working with if Statement:
1. Rely on Python's truthiness rules (if value:) instead of explicit comparisons to True, False, or empty containers
2. Keep condition expressions simple and readable — extract a well-named boolean variable or helper function for complex conditions
3. Use a guard clause to reduce nesting instead of wrapping the main logic in a large if block
Tip: Test truthiness directly, e.g. `if items:`, instead of comparing to an empty value explicitly, e.g. checking that its length is greater than zero — it's more idiomatic and works uniformly across strings, lists, dicts, and other falsy-aware types.
age = 20
if age >= 18:
print("You can vote")