Python if-else Statement
The if-else
statement in Python is used to execute a block of code if a condition is true, and a different block of code if the condition is false.
Syntax:
if condition:
# Block of code if condition is True
else:
# Block of code if condition is False
Indentation is important in Python. All code inside the
if
orelse
block should be properly indented.
Example 1: Basic if-else
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Output:
You are an adult.
Example 2: Odd or Even
number = 7
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Output:
The number is odd.
Example 3: Using Input
score = int(input("Enter your score: "))
if score >= 50:
print("You passed the test.")
else:
print("You failed the test.")
Sample Output (user enters 65):
You passed the test.
When to Use if-else
- Checking conditions and responding with two different outcomes.
- Making binary decisions (yes/no, true/false).
- Validation logic in applications.
Important Notes:
- Python uses colons (:) after
if
andelse
. - The else block is optional, but often used for fallback logic.
Flowchart
See the corrected flowchart representation of the if-else
logic:
- If condition is true → execute block 1
- If condition is false → execute block 2
- Both paths lead to the end
Practice Exercise:
Write a program to check if a number is positive or negative.
num = -5
if num >= 0:
print("Positive number")
else:
print("Negative number")
Output:
Negative number