True
or False
.To control the flow of the program depending on different conditions like:
Checking if a user is eligible to vote.
Determining whether a number is positive, negative, or zero.
Running different operations based on user input.
Python has the following types of conditional statements:
if
StatementExecutes a block of code only if the condition is True
.
age = 20
if age >= 18:
print("You are eligible to vote.")
if-else
StatementExecutes one block if condition is True
, another block if False
.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
if-elif-else
StatementUsed when you have multiple conditions to check.
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
if
StatementsYou can put an if
statement inside another if
.
age = 25
citizen = True
if age >= 18:
if citizen:
print("You can vote.")
else:
print("Only citizens can vote.")
if condition:
# code block
elif another_condition:
# code block
else:
# code block
Indentation (usually 4 spaces) is crucial.
Conditions use comparison (==
, >
, <
, etc.) and logical (and
, or
, not
) operators.
Type | Operators | Example |
---|---|---|
Comparison | == , != , > , < , >= , <= |
x >= 18 |
Logical | and , or , not |
x > 10 and x < 20 |
Membership | in , not in |
'a' in 'apple' |
Identity | is , is not |
x is None |
num = 7
if num % 2 == 0:
print("Even")
elif num % 3 == 0:
print("Divisible by 3")
else:
print("Odd and not divisible by 3")
Use meaningful variable names.
Keep conditions simple and readable.
Use parentheses ()
to group complex logical conditions.