Lesson 5 of 2011 min read

Conditional Statements

Share:WhatsAppLinkedIn

Prerequisites: Variables, Data Types, Operators, Input/Output


1. Flow of Control

The flow of control is the order in which statements are executed in a program. There are three types:

Type Description Python Construct
Sequential Statements executed one after another, top to bottom Default behavior
Conditional (Selection) Choose which statements to execute based on a condition if, if-else, if-elif-else
Iterative (Repetition) Repeat a group of statements multiple times for, while

2. Indentation in Python

Unlike C, C++, or Java (which use braces {} to define blocks), Python uses indentation (whitespace at the beginning of a line).

  • Standard indentation: 4 spaces per level, All statements in the same block must have the same indentation
  • Incorrect indentation causes IndentationError
# Example 1: Indentation matters!

# CORRECT:
if True:
 print("Line 1") # 4 spaces
 print("Line 2") # 4 spaces (same block)

# WRONG (will cause IndentationError):
# if True:
# print("Line 1")
# print("Line 2") # inconsistent indentation!

# WRONG (will cause IndentationError):
# if True:
# print("Line 1") # no indentation after if!

3. The if Statement (Simple Selection)

Executes a block of code only if the condition is True. If the condition is False, the block is skipped.

Syntax

if condition:
 statement(s) # executed only if condition is True

Flowchart Logic

 [condition]
 / \
 True False
 | |
 [execute block] [skip]
 | |
 \ /
 [continue]
# Example 2: Simple if statement
age = 18
if age >= 18:
 print("You are eligible to vote.")
 print("Please register at your local booth.")

print("Thank you!") # This runs regardless of the condition

Output:

You are eligible to vote.
Please register at your local booth.
Thank you!
# Example 3: if with False condition
age = 15
if age >= 18:
 print("You are eligible to vote.") # skipped

print("Thank you!") # runs regardless

Output:

Thank you!

4. The if-else Statement

Provides two paths: one for when the condition is True, and another for when it is False.

Syntax

if condition:
 statement(s) # executed if condition is True
else:
 statement(s) # executed if condition is False
# Example 4: if-else
num = int(input("Enter a number: "))

if num % 2 == 0:
 print(f"{num} is Even")
else:
 print(f"{num} is Odd")

Output (for input 7):

Enter a number: 7
7 is Odd

Output (for input 12):

Enter a number: 12
12 is Even

5. The if-elif-else Statement (Ladder)

Used when there are multiple conditions to check. Python checks conditions from top to bottom. The first True condition's block is executed, and the rest are skipped.

Syntax

if condition1:
 statement(s) # if condition1 is True
elif condition2:
 statement(s) # if condition2 is True
elif condition3:
 statement(s) # if condition3 is True
else:
 statement(s) # if none of the above are True
# Example 5: if-elif-else ladder
marks = int(input("Enter marks: "))

if marks >= 90:
 print("Grade: A")
elif marks >= 80:
 print("Grade: B")
elif marks >= 70:
 print("Grade: C")
elif marks >= 60:
 print("Grade: D")
else:
 print("Grade: F (Fail)")

Output (for input 85):

Enter marks: 85
Grade: B

Output (for input 55):

Enter marks: 55
Grade: F (Fail)

Important: Once a condition is True, the rest of the elif/else blocks are not checked. So if marks = 95, it matches marks >= 90 and prints "Grade: A". It does NOT also check marks >= 80 (even though 95 >= 80 is True).


6. Nested if

An if statement inside another if statement.

Syntax

if condition1:
 if condition2:
 statement(s) # both condition1 AND condition2 are True
 else:
 statement(s) # condition1 True, condition2 False
else:
 statement(s) # condition1 False
# Example 6: Nested if
num = int(input("Enter a number: "))

if num >= 0:
 if num == 0:
 print("The number is Zero")
 else:
 print("The number is Positive")
else:
 print("The number is Negative")

Output (for input 0):

Enter a number: 0
The number is Zero

Output (for input -5):

Enter a number: -5
The number is Negative

7. Short-Hand if (Ternary / Conditional Expression)

A compact way to write a simple if-else in a single line.

Syntax

value_if_true if condition else value_if_false
# Example 7: Ternary operator
num = int(input("Enter a number: "))
result = "Even" if num % 2 == 0 else "Odd"
print(result)

# Another example
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult

# Can be used directly in print
x = 10
print("Positive" if x > 0 else "Non-positive") # Positive

Output (for input 7):

Enter a number: 7
Odd
Adult
Positive

Practice Programs

Program 1: Check if Number is Positive, Negative, or Zero

num = float(input("Enter a number: "))

if num > 0:
 print(f"{num} is Positive")
elif num < 0:
 print(f"{num} is Negative")
else:
 print("The number is Zero")

Output (for input -3.5):

Enter a number: -3.5
-3.5 is Negative

Program 2: Find Largest of Three Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:
 largest = a
elif b >= a and b >= c:
 largest = b
else:
 largest = c

print(f"The largest number is {largest}")

Output:

Enter first number: 15
Enter second number: 42
Enter third number: 28
The largest number is 42

Alternative using nested if:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b:
 if a >= c:
 largest = a
 else:
 largest = c
else:
 if b >= c:
 largest = b
 else:
 largest = c

print(f"The largest number is {largest}")

Alternative using max function:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

print(f"The largest number is {max(a, b, c)}")

Program 3: Check Even or Odd

num = int(input("Enter a number: "))

if num % 2 == 0:
 print(f"{num} is Even")
else:
 print(f"{num} is Odd")

Output:

Enter a number: 13
13 is Odd

Program 4: Check Divisibility

num = int(input("Enter a number: "))
divisor = int(input("Enter divisor: "))

if divisor == 0:
 print("Error: Cannot divide by zero!")
elif num % divisor == 0:
 print(f"{num} is divisible by {divisor}")
else:
 print(f"{num} is NOT divisible by {divisor}")
 print(f"Remainder = {num % divisor}")

Output:

Enter a number: 24
Enter divisor: 6
24 is divisible by 6

Program 5: Simple Calculator

print("--- Simple Calculator ---")
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == "+":
 result = num1 + num2
 print(f"{num1} + {num2} = {result}")
elif operator == "-":
 result = num1 - num2
 print(f"{num1} - {num2} = {result}")
elif operator == "*":
 result = num1 * num2
 print(f"{num1} * {num2} = {result}")
elif operator == "/":
 if num2 == 0:
 print("Error: Division by zero!")
 else:
 result = num1 / num2
 print(f"{num1} / {num2} = {result}")
else:
 print("Invalid operator!")

Output:

--- Simple Calculator ---
Enter first number: 15
Enter operator (+, -, *, /): *
Enter second number: 4
15.0 * 4.0 = 60.0

Program 6: Grade Assignment (Marks to Grade)

marks = float(input("Enter marks (out of 100): "))

if marks < 0 or marks > 100:
 print("Invalid marks! Must be between 0 and 100.")
elif marks >= 91:
 print(f"Marks: {marks} -> Grade: A1")
elif marks >= 81:
 print(f"Marks: {marks} -> Grade: A2")
elif marks >= 71:
 print(f"Marks: {marks} -> Grade: B1")
elif marks >= 61:
 print(f"Marks: {marks} -> Grade: B2")
elif marks >= 51:
 print(f"Marks: {marks} -> Grade: C1")
elif marks >= 41:
 print(f"Marks: {marks} -> Grade: C2")
elif marks >= 33:
 print(f"Marks: {marks} -> Grade: D (Pass)")
else:
 print(f"Marks: {marks} -> Grade: E (Fail)")

Output:

Enter marks (out of 100): 76
Marks: 76.0 -> Grade: B1

Program 7: Check Leap Year

A year is a leap year if:

  • It is divisible by 4 AND
  • It is NOT divisible by 100, UNLESS it is also divisible by 400
year = int(input("Enter a year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
 print(f"{year} is a Leap Year")
else:
 print(f"{year} is NOT a Leap Year")

Output:

Enter a year: 2024
2024 is a Leap Year
Enter a year: 1900
1900 is NOT a Leap Year
Enter a year: 2000
2000 is a Leap Year

Alternative using nested if:

year = int(input("Enter a year: "))

if year % 4 == 0:
 if year % 100 == 0:
 if year % 400 == 0:
 print(f"{year} is a Leap Year")
 else:
 print(f"{year} is NOT a Leap Year")
 else:
 print(f"{year} is a Leap Year")
else:
 print(f"{year} is NOT a Leap Year")

Program 8: Check if Character is Vowel or Consonant

ch = input("Enter a single character: ")

if ch.isalpha and len(ch) == 1:
 if ch.lower in "aeiou":
 print(f"'{ch}' is a Vowel")
 else:
 print(f"'{ch}' is a Consonant")
else:
 print("Invalid input! Please enter a single alphabet character.")

Output:

Enter a single character: E
'E' is a Vowel
Enter a single character: k
'k' is a Consonant

Alternative without using .lower and in:

ch = input("Enter a character: ")

if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or \
 ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U':
 print(f"'{ch}' is a Vowel")
elif ch.isalpha:
 print(f"'{ch}' is a Consonant")
else:
 print("Not an alphabet character")

Common Mistakes

  1. Missing colon after if, elif, else: if x > 5 instead of if x > 5: causes SyntaxError
  2. Using = instead of ==: if x = 5: (assignment) instead of if x == 5: (comparison). Python 3 catches this as SyntaxError
  3. Wrong indentation: All statements in a block must be at the same level. Mixing tabs and spaces causes errors
  4. Forgetting elif and using else if: Python uses elif, not else if. Writing else if creates a nested structure (which is different)
  5. Using elif after else: else must be the last clause. Having elif after else is a SyntaxError
  6. Not handling all cases: Forgetting edge cases like zero, negative numbers, or division by zero
  7. Dangling else confusion: In nested if-else, the else belongs to the nearest unmatched if. Use proper indentation to make it clear
  8. Using and when or is needed (and vice versa): "If age is less than 13 or greater than 19" needs or, not and
  9. Redundant conditions in elif: After if marks >= 90, writing elif marks >= 80 and marks < 90 is redundant. Just elif marks >= 80 is enough (because if marks were >= 90, it would have been caught by the first if)
  10. Comparing strings case-sensitively without realizing: input returns exactly what the user types. "Yes" != "yes" != "YES". Use .lower for case-insensitive comparison

$1$2 Quick Tips

  1. Find the output (2-4 marks): The most common question. Given a code snippet with if-elif-else, predict the output. Trace through the conditions carefully
  2. Write a program (3-5 marks): Leap year, largest of three, grade assignment, calculator, practice all of these
  3. Identify errors (1-2 marks): Missing colon, wrong indentation, = vs ==, elif after else
  4. Rewrite using if-elif-else (2-3 marks): Convert nested if to if-elif-else ladder or vice versa
  5. Ternary expression (1-2 marks): "Rewrite using a conditional expression" or "What is the output?"
  6. Flowchart to code (2-3 marks): Convert a given flowchart into Python code
  7. Nested if questions (2-3 marks): Carefully trace which else belongs to which if
  8. Leap year logic (3-4 marks): Both the flat version (using and/or) and nested version are important
  9. "What is the difference between if-else and if-elif-else?" (2 marks): if-else has two paths; if-elif-else has multiple paths. elif allows checking additional conditions without nesting
  10. Indentation questions (1-2 marks): "Why is indentation important in Python?" or "What error occurs with wrong indentation?"

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube