An if statement is used to execute a block of code only if a specified condition is true.
Syntax
if condition:
# code to execute
Simple If Statement
Example:
age = 18
if age >= 18:
print("You are an adult")
Output:
You are an adult
How It Works
The condition is evaluated first.
- If the condition is
True, the code block runs. - If the condition is
False, the code block is skipped.
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
Using Comparison Operators
Comparison operators are commonly used with if statements.
| Operator | Description |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example:
number = 20
if number == 20:
print("Number is 20")
Output:
Number is 20
Using Variables
Example:
name = "John"
if name == "John":
print("Welcome John")
Output:
Welcome John
Multiple Statements
You can execute multiple statements inside an if block.
Example:
age = 25
if age >= 18:
print("You are an adult")
print("You can vote")
Output:
You are an adult
You can vote
Using Logical Operators
Example:
age = 25
if age >= 18 and age <= 60:
print("Eligible")
Output:
Eligible
Nested If Statement
You can place one if statement inside another.
Example:
age = 25
if age >= 18:
if age >= 21:
print("Access Granted")
Output:
Access Granted
If with Boolean Values
Example:
is_logged_in = True
if is_logged_in:
print("Welcome")
Output:
Welcome
Short Hand If
If you have only one statement to execute, you can write it on one line.
Example:
age = 18
if age >= 18: print("Adult")
Output:
Adult
Practical Example
Check if a number is positive.
Example:
number = 10
if number > 0:
print("Positive Number")
Output:
Positive Number
Common Mistake
Missing indentation:
age = 18
if age >= 18:
print("Adult")
Output:
IndentationError: expected an indented block
Correct:
age = 18
if age >= 18:
print("Adult")
Summary
- The
ifstatement executes code when a condition isTrue. - Conditions are evaluated using comparison operators.
- Indentation is required inside
ifblocks. - Multiple statements can be placed inside an
ifblock. - Logical operators such as
and,or, andnotcan be used. ifstatements can be nested inside otherifstatements.