Conditional Statements
Definition: Conditional statements are used to perform different actions based on different conditions. They allow a program to make decisions and execute specific blocks of code only when certain criteria are met.
Why: Decision-making is the heart of programming logic. Without these statements, a program would simply run every line of code in order without ever reacting to different inputs or situations.
1. The IF Statement
The if statement is the most basic form of decision-making. If the condition is true, the code block inside it runs.
if condition:
# code to executex = 10
if x > 5:
print("x is greater than 5")
2. The ELIF Statement
Short for "else if," this is used to check a new condition if the previous if condition was false.
elif another_condition:
# code to executemarks = 75
if marks >= 90:
print("Excellent")
elif marks >= 70:
print("Very Good")
3. The ELSE Statement
The else statement catches anything that wasn't caught by the preceding if or elif conditions. It does not take a condition of its own.
else:
# code to executeage = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
4. Shorthand If & If...Else
If you have only one statement to execute, you can put it on the same line as the if statement. You can also write an entire if-else block in one line.
if condition: statementresult_if_true if condition else result_if_false# Shorthand If
if 10 > 5: print("10 is greater than 5")
# Shorthand If...Else
print("Pass") if marks >= 35 else print("Fail")
5. Nested If
You can have if statements inside other if statements. This is called nesting.
if condition1:
if condition2:
# code to executenum = 15
if num > 10:
print("Above ten,")
if num > 20:
print("and also above 20!")
else:
print("but not above 20.")
Key Notes
- Indentation: Python relies on indentation (whitespace at the beginning of a line) to define the scope of the code block. Forgetting this will result in an error.
- Colons: Every
if,elif, andelseline must end with a colon (:). - Boolean Logic: Conditions always evaluate to either
TrueorFalse.
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Conditional Statements to test your knowledge.
Exercise »