Python if Statement
3 min read ·
The
if statement is a decision-making statement.
It allows Python to execute code only when a condition is True.In simple words:
If condition is true → code runs If condition is false → code is skipped
Basic Syntax of if
ifkeyword starts the condition- Condition must return
TrueorFalse - Colon
:is mandatory - Indentation defines the block
Note
The code inside if must be indented, otherwise Python will throw an error.
First Example – Simple if Statement
- Condition:
age >= 18 - If condition is
True, print statement executes - If condition is
False, nothing happens
if Statement with Boolean Condition
- No comparison needed
- Python directly checks the boolean value
if Statement with Comparison Operators
Common Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Example
if Statement with Strings
Caution
String comparison is case-sensitive.
"Python" and "python" are not the same.
Multiple Conditions using Logical Operators
and Operator
Both conditions must be
True.or Operator
At least one condition must be
True.not Operator
Nested if Statement
An
if inside another if.- Outer
ifchecks positivity - Inner
ifchecks even number
Pro Tip
Avoid deep nesting. It makes code hard to read.
if Statement with User Input
input()returns stringint()converts it into integer
if Statement with Mathematical Logic
Common Mistakes in if Statement
Missing Colon ❌
Wrong Indentation ❌
Stop
Python will throw SyntaxError or IndentationError in these cases.
Real World Example
Real World Scenario
ATM Machine Condition If balance is sufficient → allow withdrawal
Exercise
Practice Task
- Take a number and check if it is greater than 100
- Check if a number is even
- Create a login check using a boolean variable
- Try nesting one
ifinside another