if Statement
The if
statement executes a block of code if a specified condition is True
.
Python
age = 18
if age >= 18:
print("You are an adult")
if-else Statement
The if-else
statement provides an alternative block of code to be executed if the condition is False
.
Python
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
if-elif-else Statement
The elif
statement allows you to check multiple conditions sequentially.
Python
age = 13
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Key Points
- Conditions are expressions that evaluate to
True
orFalse
. - Indentation is crucial for defining code blocks within
if
,elif
, andelse
statements. - You can nest
if
statements within otherif
statements for complex logic. - The
else
block is optional.
What is an if statement?
An if statement executes a block of code if a specified condition is true.
What is the purpose of else?
The else block is executed if the if condition is false.
What is the purpose of elif?
Elif allows for multiple conditional checks.
How do I check multiple conditions?
Use elif statements for multiple conditions.
What happens if no condition is true?
The else block is executed if no previous conditions are true.
How can I improve readability of conditional statements?
Use clear and concise variable names, add comments, and consider breaking down complex conditions into smaller ones.
Can I nest if statements?
Yes, you can nest if statements for complex logic.
When should I use if-else vs. ternary operator?
Ternary operators are suitable for simple conditions, while if-else statements are better for complex logic.