Python Programming | Decision Control Statements BE 2nd Semester
PYTHON PROGRAMMING
Lecture Notes
Unit: Decision Control Statements
B.E. (Computer Science / Information Science) | 2nd Semester
Academic Year 2024–25
Topics Covered:
1. Introduction to Decision Control Statements
2. Selection Statements: if, if-else, if-elif-else
3. Conditional (Ternary) Expressions
4. Iterative Statements: for and while loops
5. Nested Loops
6. break, continue, and pass Statements
1. Introduction to Decision Control Statements
1.1 What are Control Statements?
In Python, statements are executed sequentially by default — one after another. However, real-world
problems require decisions, repetitions, and alternate paths. Decision control statements allow a
program to alter this flow based on conditions.
Definition:
A control statement determines which other statements are executed and
in what order.
They allow a program to make decisions, repeat tasks, and skip
instructions.
1.2 Types of Control Statements
Category Statements Purpose
Conditional / Selection if, if-else, if-elif-else Execute a block based on a condition
Iterative / Looping for, while Repeat a block multiple times
Jump Statements break, continue, pass Alter flow inside loops
Page 1
Python Programming | Decision Control Statements BE 2nd Semester
2. Selection and Conditional Branching Statements
2.1 The if Statement
The simplest decision-making statement. It executes a block of code only when the given condition is
True.
Syntax:
if <condition>:
statement(s)
Note: Python uses indentation (4 spaces) to define blocks — no curly
braces.
Example 1 — Check Positive Number
1 num = int(input('Enter a number: '))
2 if num > 0:
3 print('The number is positive')
4 print('End of program')
Explanation: The print inside the if block runs only when num > 0. The last line always runs
regardless of the condition.
2.2 The if-else Statement
Provides two alternative paths — one when the condition is True, another when it is False.
Syntax:
if <condition>:
statement(s) # runs when condition is True
else:
statement(s) # runs when condition is False
Example 2 — Even or Odd
1 num = int(input('Enter a number: '))
2 if num % 2 == 0:
3 print(num, 'is Even')
4 else:
5 print(num, 'is Odd')
Example 3 — Voting Eligibility
Page 2
Python Programming | Decision Control Statements BE 2nd Semester
1 age = int(input('Enter your age: '))
2 if age >= 18:
3 print('You are eligible to vote')
4 else:
5 print('You are NOT eligible to vote')
2.3 The if-elif-else Statement
Used when there are more than two conditions to check. Python evaluates each condition from top to
bottom and executes the first matching block.
Syntax:
if <condition1>:
statement(s)
elif <condition2>:
statement(s)
elif <condition3>:
statement(s)
else:
statement(s) # default, runs if none of the above is True
Example 4 — Grade Calculator
1 marks = int(input('Enter your marks (0-100): '))
2
3 if marks >= 90:
4 grade = 'O (Outstanding)'
5 elif marks >= 75:
6 grade = 'A (Excellent)'
7 elif marks >= 60:
8 grade = 'B (Good)'
9 elif marks >= 50:
10 grade = 'C (Average)'
11 elif marks >= 35:
12 grade = 'D (Pass)'
13 else:
14 grade = 'F (Fail)'
15
16 print(f'Your Grade: {grade}')
Example 5 — Largest of Three Numbers
1 a = int(input('Enter first number: '))
2 b = int(input('Enter second number: '))
3 c = int(input('Enter third number: '))
4
5 if a >= b and a >= c:
6 print(a, 'is the largest')
Page 3
Python Programming | Decision Control Statements BE 2nd Semester
7 elif b >= a and b >= c:
8 print(b, 'is the largest')
9 else:
10 print(c, 'is the largest')
2.4 Nested if Statements
An if statement placed inside another if statement is called a nested if. It is used when a second
condition needs to be checked only after the first is satisfied.
Example 6 — Nested if
1 num = int(input('Enter a number: '))
2
3 if num != 0:
4 if num > 0:
5 print('Positive number')
6 else:
7 print('Negative number')
8 if num % 2 == 0:
9 print('Even number')
10 else:
11 print('Odd number')
12 else:
13 print('The number is Zero')
2.5 Conditional (Ternary) Expression
A shorthand way to write a simple if-else in a single line.
Syntax:
value_if_true if <condition> else value_if_false
Example 7 — Ternary Expression
1 age = int(input('Enter age: '))
2 status = 'Adult' if age >= 18 else 'Minor'
3 print(f'Status: {status}')
4
5 x, y = 10, 20
6 larger = x if x > y else y
7 print(f'Larger value: {larger}')
Practice Questions — Selection Statements
Page 4
Python Programming | Decision Control Statements BE 2nd Semester
Q1. Write a Python program to check whether a year is a leap year or not.
# A year is a leap year if divisible by 4 AND (not by 100 OR divisible by
400)
year = int(input('Enter year: '))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, 'is a Leap Year')
else:
print(year, 'is NOT a Leap Year')
Q2. Write a program to find if a character is a vowel, consonant, digit, or special
character.
ch = input('Enter a character: ')
if [Link]():
print('It is a Digit')
elif [Link]():
if [Link]() in 'aeiou':
print('It is a Vowel')
else:
print('It is a Consonant')
else:
print('It is a Special Character')
Q3. Write a program to calculate income tax based on slabs: Up to 2.5L: 0%, 2.5-5L:
5%, 5-10L: 20%, Above 10L: 30%.
income = float(input('Enter annual income in lakhs: '))
if income <= 2.5:
tax = 0
elif income <= 5:
tax = (income - 2.5) * 0.05
elif income <= 10:
tax = (2.5 * 0.05) + (income - 5) * 0.20
else:
tax = (2.5 * 0.05) + (5 * 0.20) + (income - 10) * 0.30
print(f'Tax payable: Rs. {tax:.2f} Lakhs')
Q4. Using the ternary expression, find the absolute value of a number without using
abs().
num = float(input('Enter a number: '))
absolute = num if num >= 0 else -num
print(f'Absolute value: {absolute}')
Q5. Display the day name for a given day number (1=Monday to 7=Sunday) using if-
elif-else.
Page 5
Python Programming | Decision Control Statements BE 2nd Semester
day = int(input('Enter day number (1-7): '))
if day == 1: print('Monday')
elif day == 2: print('Tuesday')
elif day == 3: print('Wednesday')
elif day == 4: print('Thursday')
elif day == 5: print('Friday')
elif day == 6: print('Saturday')
elif day == 7: print('Sunday')
else: print('Invalid day number')
3. Iterative Statements (Loops)
A loop allows a block of code to execute repeatedly until a condition is met. Python provides two
types of loops: for and while.
3.1 The for Loop
The for loop iterates over a sequence (list, tuple, string, range, etc.). The loop variable takes each
value in the sequence one at a time.
Syntax:
for <variable> in <sequence>:
statement(s)
# Optional else clause (runs after loop finishes, NOT after a break):
for <variable> in <sequence>:
statement(s)
else:
statement(s)
Example 8 — Using range()
1 # range(stop) -> 0 to stop-1
2 # range(start, stop) -> start to stop-1
3 # range(start, stop, step) -> with custom step
4
5 for i in range(1, 6):
6 print(i, end=' ') # Output: 1 2 3 4 5
7
8 print()
9
10 for i in range(10, 0, -2):
11 print(i, end=' ') # Output: 10 8 6 4 2
Example 9 — Iterating Over a String
Page 6
Python Programming | Decision Control Statements BE 2nd Semester
1 name = 'Python'
2 for char in name:
3 print(char, end='-')
4 # Output: P-y-t-h-o-n-
Example 10 — Sum of First N Natural Numbers
1 n = int(input('Enter n: '))
2 total = 0
3 for i in range(1, n + 1):
4 total += i
5 print(f'Sum of first {n} natural numbers = {total}')
Example 11 — Multiplication Table
1 num = int(input('Enter a number: '))
2 for i in range(1, 11):
3 print(f'{num} x {i:2d} = {num * i}')
Example 12 — for-else (Prime Number Check)
1 num = int(input('Enter a number: '))
2 if num < 2:
3 print('Not a prime number')
4 else:
5 for i in range(2, int(num**0.5) + 1):
6 if num % i == 0:
7 print(f'{num} is NOT a prime number')
8 break
9 else:
10 print(f'{num} IS a prime number')
3.2 The while Loop
The while loop executes a block of code as long as its condition remains True. It is used when the
number of iterations is not known in advance.
Syntax:
while <condition>:
statement(s)
Warning: Always ensure the condition eventually becomes False.
Forgetting to update the loop variable causes an INFINITE LOOP.
Example 13 — Basic while Loop
1 count = 1
2 while count <= 5:
Page 7
Python Programming | Decision Control Statements BE 2nd Semester
3 print(f'Count: {count}')
4 count += 1 # update the variable to avoid infinite loop
5 print('Loop ended')
Example 14 — Reverse of a Number
1 num = int(input('Enter a number: '))
2 original = num
3 reverse = 0
4
5 while num > 0:
6 digit = num % 10 # extract last digit
7 reverse = reverse * 10 + digit
8 num = num // 10 # remove last digit
9
10 print(f'Reverse of {original} is {reverse}')
Example 15 — Factorial using while
1 n = int(input('Enter a number: '))
2 fact = 1
3 i = 1
4 while i <= n:
5 fact *= i
6 i += 1
7 print(f'{n}! = {fact}')
Example 16 — Fibonacci Series
1 n = int(input('How many Fibonacci terms? '))
2 a, b = 0, 1
3 count = 0
4 while count < n:
5 print(a, end=' ')
6 a, b = b, a + b
7 count += 1
Practice Questions — Iterative Statements
Q6. Write a program to print all prime numbers between 1 and 100.
for num in range(2, 101):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
Page 8
Python Programming | Decision Control Statements BE 2nd Semester
if is_prime:
print(num, end=' ')
Q7. Write a program using a while loop to find the sum of digits of a given number.
num = int(input('Enter a number: '))
digit_sum = 0
temp = abs(num)
while temp > 0:
digit_sum += temp % 10
temp //= 10
print(f'Sum of digits of {num} = {digit_sum}')
Q8. Count the number of vowels in a string using a for loop.
text = input('Enter a string: ')
vowels = 'aeiouAEIOU'
count = 0
for ch in text:
if ch in vowels:
count += 1
print(f'Number of vowels = {count}')
Q9. Print the series 1 + 1/2 + 1/3 + ... + 1/N and display the sum.
n = int(input('Enter N: '))
total = 0
for i in range(1, n + 1):
total += 1 / i
print(f'Sum = {total:.4f}')
Q10. Check if a number is an Armstrong number (e.g., 153 = 1^3 + 5^3 + 3^3).
num = int(input('Enter a number: '))
order = len(str(num))
temp, arm_sum = num, 0
while temp > 0:
digit = temp % 10
arm_sum += digit ** order
temp //= 10
if arm_sum == num:
print(f'{num} IS an Armstrong number')
else:
print(f'{num} is NOT an Armstrong number')
Page 9
Python Programming | Decision Control Statements BE 2nd Semester
4. Nested Loops
A nested loop is a loop placed inside another loop. The inner loop runs completely for each single
iteration of the outer loop.
Execution Rule:
For each iteration of the OUTER loop:
The INNER loop runs through ALL its iterations.
Total iterations = outer_count x inner_count
4.1 Nested for Loops — Patterns
Example 17 — Right-Angled Star Pattern
1 n = 5
2 for i in range(1, n + 1): # outer: rows
3 for j in range(1, i + 1): # inner: columns
4 print('*', end=' ')
5 print() # newline after each row
6
7 # Output:
8 # *
9 # * *
10 # * * *
11 # * * * *
12 # * * * * *
Example 18 — Number Pattern
1 n = 5
2 for i in range(1, n + 1):
3 for j in range(1, i + 1):
4 print(j, end=' ')
5 print()
6
7 # Output:
8 # 1
9 # 1 2
10 # 1 2 3
11 # 1 2 3 4
12 # 1 2 3 4 5
Example 19 — Inverted Star Pattern
1 n = 5
2 for i in range(n, 0, -1):
3 for j in range(i):
4 print('*', end=' ')
Page 10
Python Programming | Decision Control Statements BE 2nd Semester
5 print()
Example 20 — Matrix Multiplication
1 A = [[1, 2], [3, 4]]
2 B = [[5, 6], [7, 8]]
3 rows, cols = len(A), len(B[0])
4 C = [[0] * cols for _ in range(rows)]
5
6 for i in range(rows):
7 for j in range(cols):
8 for k in range(len(B)):
9 C[i][j] += A[i][k] * B[k][j]
10
11 for row in C:
12 print(row)
Practice Questions — Nested Loops and Patterns
Q11. Write a program to print a pyramid pattern of stars for n = 5.
n = 5
for i in range(1, n + 1):
print(' ' * (n - i), end='')
print('* ' * i)
Q12. Print a 5x5 multiplication table grid using nested loops.
print(' ', end='')
for j in range(1, 6):
print(f'{j:4}', end='')
print()
print('-' * 24)
for i in range(1, 6):
print(f'{i} |', end='')
for j in range(1, 6):
print(f'{i*j:4}', end='')
print()
Q13. Write a program to find all pairs (i, j) such that i + j = 10, where 1 <= i, j <= 10.
for i in range(1, 10):
for j in range(1, 10):
if i + j == 10:
print(f'({i}, {j})', end=' ')
Page 11
Python Programming | Decision Control Statements BE 2nd Semester
Q14. Write a program to print Pascal's Triangle up to N rows.
n = int(input('Enter number of rows: '))
for i in range(n):
coeff = 1
print(' ' * (n - i - 1), end='')
for j in range(i + 1):
print(coeff, end=' ')
coeff = coeff * (i - j) // (j + 1)
print()
5. break, continue, and pass Statements
These are jump statements that alter the normal flow of execution within loops.
5.1 The break Statement
The break statement immediately terminates the loop it is in. Execution continues from the first
statement after the loop. When used in nested loops, break exits only the innermost loop.
Key Rule:
break exits only the NEAREST enclosing loop.
The for-else / while-else block does NOT run if the loop exits via
break.
Example 21 — break in for loop
1 for num in range(1, 50):
2 if num % 7 == 0:
3 print(f'First multiple of 7: {num}')
4 break
Example 22 — break in while loop (Password Validation)
1 while True: # intentional infinite loop
2 password = input('Enter password: ')
3 if password == 'secret123':
4 print('Access Granted!')
5 break
6 else:
7 print('Wrong password. Try again.')
Example 23 — break in Nested Loop
1 for i in range(1, 4):
2 for j in range(1, 4):
Page 12
Python Programming | Decision Control Statements BE 2nd Semester
3 if j == 2:
4 break # exits inner loop only
5 print(f'i={i}, j={j}')
6 print(f'Outer loop i={i} continues')
7
8 # Output:
9 # i=1, j=1
10 # Outer loop i=1 continues
11 # i=2, j=1
12 # Outer loop i=2 continues
13 # i=3, j=1
14 # Outer loop i=3 continues
5.2 The continue Statement
The continue statement skips the rest of the current iteration and moves to the next iteration. It does
NOT exit the loop.
Key Rule:
continue skips the REMAINING statements in the current iteration only.
The loop then proceeds with the next iteration normally.
Example 24 — Printing Only Odd Numbers
1 for i in range(1, 11):
2 if i % 2 == 0:
3 continue # skip even numbers
4 print(i, end=' ')
5 # Output: 1 3 5 7 9
Example 25 — continue in while loop
1 total = 0
2 count = 0
3 while count < 5:
4 num = int(input('Enter a number: '))
5 count += 1
6 if num < 0:
7 print('Negative number ignored!')
8 continue # skip adding this number
9 total += num
10 print(f'Sum of positive numbers: {total}')
5.3 The pass Statement
The pass statement is a null operation — it does nothing. It is used as a placeholder where a
statement is syntactically required but no code needs to run yet.
Page 13
Python Programming | Decision Control Statements BE 2nd Semester
When to use pass:
1. Placeholder for future code
2. Empty function or class definition
3. Loop body that intentionally does nothing
4. Stub programming (writing structure before filling logic)
Example 26 — pass as a Placeholder
1 for i in range(1, 6):
2 if i == 3:
3 pass # will handle this case later
4 else:
5 print(i, end=' ')
6 # Output: 1 2 4 5
Example 27 — pass in Function and Class
1 def future_function():
2 pass # implementation pending
3
4 class EmptyClass:
5 pass # class body to be added later
5.4 Comparison: break vs continue vs pass
Feature break continue pass
Effect on loop Exits loop Skips current iteration No effect
immediately
Loop continues? No Yes (next iteration) Yes (same iteration)
Remaining All skipped Current iteration None skipped
statements skipped
In nested loops Exits innermost only Skips innermost No special behavior
iteration
Common use Stop when target Skip unwanted values Empty placeholder
found blocks
Practice Questions — break, continue, and pass
Q15. Write a program using break to find the first number between 1 and 100 divisible
by both 3 and 5.
for num in range(1, 101):
Page 14
Python Programming | Decision Control Statements BE 2nd Semester
if num % 3 == 0 and num % 5 == 0:
print(f'First number: {num}')
break
Q16. Write a program using continue to print numbers from 1 to 20 that are NOT
divisible by 3.
for i in range(1, 21):
if i % 3 == 0:
continue
print(i, end=' ')
Q17. Take 5 subject marks as input. Use continue to skip invalid marks (>100 or <0),
then print the average.
total, valid = 0, 0
for i in range(5):
mark = int(input(f'Subject {i+1}: '))
if mark < 0 or mark > 100:
print('Invalid, skipping...')
continue
total += mark
valid += 1
if valid > 0:
print(f'Average: {total/valid:.2f}')
else:
print('No valid marks entered')
Q18. From 1 to 50, print numbers not divisible by 2 or 3, and stop when count reaches
10.
count = 0
for num in range(1, 51):
if num % 2 == 0 or num % 3 == 0:
continue
print(num, end=' ')
count += 1
if count == 10:
break
Q19. Demonstrate pass by writing skeleton code for a calculator where only addition
is implemented.
def add(a, b): return a + b
def subtract(a, b): pass # TODO
def multiply(a, b): pass # TODO
def divide(a, b): pass # TODO
Page 15
Python Programming | Decision Control Statements BE 2nd Semester
a, b = 10, 5
op = input('Enter operation (+, -, *, /): ')
if op == '+':
print(f'Result: {add(a, b)}')
elif op in ['-', '*', '/']:
pass # not yet implemented
else:
print('Unknown operation')
6. Advanced Mixed Practice Problems
Q20. Generate all Pythagorean triplets where a, b, c <= 20.
for a in range(1, 21):
for b in range(a, 21):
for c in range(b, 21):
if a**2 + b**2 == c**2:
print(f'({a}, {b}, {c})')
Q21. Implement a simple number guessing game using a while loop.
import random
secret = [Link](1, 100)
attempts = 0
while True:
guess = int(input('Your guess: '))
attempts += 1
if guess < secret:
print('Too low!')
elif guess > secret:
print('Too high!')
else:
print(f'Correct! Guessed in {attempts} attempts!')
break
Q22. Print all perfect numbers between 1 and 500. (A perfect number equals the sum
of its proper divisors.)
for num in range(1, 501):
div_sum = sum(i for i in range(1, num) if num % i == 0)
if div_sum == num:
print(num)
Q23. Print a diamond pattern of stars for n = 5.
Page 16
Python Programming | Decision Control Statements BE 2nd Semester
n = 5
for i in range(1, n + 1): # upper half
print(' ' * (n - i) + '* ' * i)
for i in range(n - 1, 0, -1): # lower half
print(' ' * (n - i) + '* ' * i)
Q24. Write a menu-driven program for number operations using while, break, and
continue.
while True:
print('\n1. Prime Check 2. Factorial 3. Reverse 4. Exit')
choice = int(input('Choice: '))
if choice == 4:
print('Goodbye!')
break
if choice not in [1, 2, 3]:
print('Invalid!')
continue
n = int(input('Enter a number: '))
if choice == 1:
prime = all(n % i != 0 for i in range(2, int(n**0.5)+1)) and n > 1
print('Prime' if prime else 'Not Prime')
elif choice == 2:
f = 1
for i in range(1, n+1): f *= i
print(f'Factorial: {f}')
elif choice == 3:
print(f'Reverse: {str(n)[::-1]}')
7. Summary
Statement Purpose When to use Syntax
if Single branch One condition if cond:
if-else Two branches True/False outcomes if cond: ... else:
if-elif-else Multi branch Multiple conditions if / elif / else
for Definite loop Known iterations for x in seq:
while Indefinite loop Unknown iterations while cond:
break Exit loop Stop early break
continue Skip iteration Skip certain values continue
pass Placeholder Empty block needed pass
Page 17
Python Programming | Decision Control Statements BE 2nd Semester
Important Points to Remember:
1. Python uses indentation (not braces) to define code blocks.
2. Use for when the number of iterations is known; use while when it
depends on a condition.
3. break exits the loop; continue skips the current iteration; pass
does nothing.
4. for/while loops have an optional else clause that runs only if NOT
exited via break.
5. Always update the condition variable in a while loop to avoid
infinite loops.
6. Nested loops execute: outer_iterations x inner_iterations times in
total.
Page 18