Conditional Statements in Python
Learn how to make decisions in your programs using if, elif, and else.
Introduction
Conditional statements allow your program to perform different actions based on certain conditions.
In Python, we use if, elif (else if), and else for decision-making.
Syntax Structure
if condition:
# code to execute if condition is True
elif another_condition:
# code to execute if another_condition is True
else:
# code to execute if all above conditions are False
Example:
age = 18
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Common Mistakes and Errors
-
Case-Sensitivity: Python keywords must be lowercase.
Writing
If,Elif, orElsewill throw an error.If age >= 18: print("You can vote")SyntaxError: invalid syntax -
Missing colon at the end of
iforelif:if age >= 18 print("You can vote")SyntaxError: expected ':' -
Wrong indentation:
if age >= 18: print("You can vote")
✅ Correct:IndentationError: expected an indented blockif age >= 18: print("You can vote") -
Using assignment
=instead of comparison==:if age = 18: print("You are 18")SyntaxError: invalid syntax -
Using
elifwithout a previousif:elif age >= 18: print("You can vote")SyntaxError: invalid syntax
Nested Conditions
You can place an if or else inside another if to make complex decisions:
age = 20
citizen = True
if age >= 18:
if citizen:
print("You can vote")
else:
print("You are not a citizen")
else:
print("You cannot vote")
💡 Try It Yourself
- Ask the user for their age and print whether they are a child, teenager, or adult using
if-elif-else. - Write a program to check if a number is positive, negative, or zero.
- Combine two conditions: ask for age and citizenship, print if they can vote or not (nested if).
What’s Next?
Now that you know basic conditionals, the next topic is Nested Conditions — learning how to handle multiple layers of decisions.
No comments:
Post a Comment