In programming, we often need to make decisions.
Examples:
- If marks are greater than 40 → Pass
- If age is greater than 18 → Eligible
- If number is even → Print “Even”
To handle such situations, we use conditional statements.
Conditional statements allow the program to execute code based on conditions.
The if statement checks a condition.
If the condition is True, the block of code runs.
Syntax:
if condition:
statementExample:
age = 20
if age > 18:
print("Eligible to vote")If the condition is false, nothing happens.
Python uses indentation (spaces) to define blocks.
Correct:
if 5 > 3:
print("Correct")Wrong:
if 5 > 3:
print("Correct") # ErrorAlways use proper indentation.
If the condition is True → first block runs If False → else block runs
Syntax:
if condition:
statement
else:
statementExample:
num = 7
if num % 2 == 0:
print("Even")
else:
print("Odd")Used when there are multiple conditions.
Syntax:
if condition1:
statement
elif condition2:
statement
else:
statementExample:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")Python checks conditions from top to bottom.
An if statement inside another if statement.
Example:
age = 22
citizen = True
if age > 18:
if citizen:
print("Eligible to vote")You can combine conditions using:
andornot
Example:
age = 20
has_id = True
if age > 18 and has_id:
print("Entry allowed")- Using
=instead of==
if age = 18: # WrongCorrect:
if age == 18:-
Wrong indentation
-
Forgetting colon
:after condition
- Take a number and check if it is positive or negative
- Take marks and print grade
- Check if a number is divisible by 5
- Take age and check if eligible to vote
Example:
num = int(input("Enter number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")