Python if Statement
Python if
Statement
The if
statement in Python is used to execute a block of code only if a specific condition is true. It is the simplest form of decision-making in programming.
Syntax of if
Statement
if condition:
# code to execute if condition is True
condition
: An expression that returnsTrue
orFalse
.- Indentation is important in Python. The indented block after
if
is only executed if the condition isTrue
.
Example 1 – Basic if
Statemen
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
Example 2 – Nothing Happens if Condition is False
x = 3
if x > 5:
print("x is greater than 5")
Output:
# (No output because the condition is False)
Example 3 – Multiple if
Statements
num = 15
if num > 0:
print("Positive number")
if num % 3 == 0:
print("Divisible by 3")
Output:
Positive number
Divisible by 3
Here, both conditions are checked separately and both are true, so both blocks execute.
Example 4 – Boolean Variables in if
is_logged_in = True
if is_logged_in:
print("Welcome, user!")
Output:
Welcome, user!
Boolean values (True
or False
) can be used directly in conditions.
Python treats these as False
in if
:
False
None
0
,0.0
''
(empty string)[]
,{}
,set()
(empty collections)
name = ""
if name:
print("Hello, " + name)
Output:
# No output, because name is an empty string
Key Points
- Use
if
to run code only when a condition is true. - Indentation is critical — don't forget to indent the block under
if
. - Python skips the block if the condition is false — no error, just nothing runs.
Mini Practice
Check if a number is even:
number = 8
if number % 2 == 0:
print("Even number")