Python If...Else Statements
The if
statement is used for decision-making operations. It contains a logical expression that evaluates to either True
or False
. Python supports the usual logical conditions from mathematics:
- Equals:
a == b
- Not Equals:
a != b
- Less than:
a < b
- Less than or equal to:
a <= b
- Greater than:
a > b
- Greater than or equal to:
a >= b
Example 1: Simple If Statement
Check if a number is positive.
# Simple if statement
number = 5
if number > 0:
print("The number is positive.")
The number is positive.
Example 2: If...Else Statement
Determine if a person is eligible to vote based on age.
# If...else statement
age = 17
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
You are not eligible to vote.
Example 3: If...Elif...Else Statement
Classify a number as positive, negative, or zero.
# If...elif...else statement
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print("Zero")
else:
print("Negative number")
Zero
Example 4: Nested If Statements
Check if a person is eligible to drive based on age and possession of a driving license.
# Nested if statements
age = 20
has_license = True
if age >= 18:
if has_license:
print("You can drive.")
else:
print("You need a driving license.")
else:
print("You are too young to drive.")
You can drive.
Example 5: Using Logical Operators
Check if a student has passed based on marks in two subjects.
# Using logical operators
math_mark = 85
science_mark = 92
if math_mark >= 50 and science_mark >= 50:
print("Student has passed.")
else:
print("Student has failed.")
Student has passed.
Explanation: The if
statement evaluates the condition and executes the code block if the condition is True
. The elif
and else
statements provide additional conditions and code blocks.