Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 5: Flow of Control

Usually, a Python program executes instructions sequentially from top to bottom. However, sometimes we need to skip instructions, choose between alternative paths, or repeat a block of code multiple times. This is managed by control flow statements.

Python relies heavily on indentation (whitespace at the beginning of a line) to define blocks of code.

5.1 Conditional Statements

Conditional statements allow a program to make decisions based on whether a condition evaluates to True or False.

The if Statement

Executes a block of code only if the condition is True.

x = 10
if x > 0:
    print("x is positive")

The if-else Statement

Provides an alternative path if the condition is False.

x = -5
if x >= 0:
    print("Positive or Zero")
else:
    print("Negative")

The if-elif-else Statement

Used to check multiple conditions sequentially. elif stands for “else if”.

marks = 85
if marks >= 90:
    print("Grade A")
elif marks >= 80:
    print("Grade B")
else:
    print("Grade C or below")

Example Program: Absolute Value

n = int(input("Enter a number: "))
if n < 0:
    n = n * -1
print("Absolute value is:", n)

5.2 Iterative Statements (Loops)

Loops are used to execute a block of code repeatedly as long as a specified condition is met.

The for Loop and range() function

The for loop is typically used to iterate over a sequence (like a list, string, or a range of numbers). The range(start, stop, step) function generates a sequence of numbers. It stops before the stop value.

# Prints numbers from 1 to 5
for i in range(1, 6):
    print(i)

The while Loop

Repeats a block of code as long as a condition remains True.

count = 1
while count <= 5:
    print(count)
    count += 1

break and continue Statements

  • break: Terminates the loop entirely and transfers execution to the statement immediately following the loop.
  • continue: Skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.

Nested Loops

A loop inside another loop.

# Generating a simple pattern
for i in range(1, 4):          # Outer loop for rows
    for j in range(1, i + 1):  # Inner loop for columns
        print("*", end="")
    print()                    # Move to the next line

Competency Based Questions

Q1. Predict the Output What will be the output of the following code snippet?

for i in range(1, 10, 2):
    if i == 5:
        continue
    print(i, end=" ")

Q2. Find the Error Ankush wants to write a while loop that prints numbers from 10 down to 1. Identify the logical error in his code.

n = 10
while n > 0:
    print(n)
    n = n + 1

Q3. Application-Oriented Write a Python program using a for loop to calculate the factorial of a positive integer N input by the user. (Note: Factorial of 5 = 5 * 4 * 3 * 2 * 1 = 120).

Q4. Assertion-Reasoning

  • Assertion (A): An if statement can exist without an else statement, but an else statement cannot exist without an if statement.
  • Reason (R): The else block serves as a default fallback option that only executes when the preceding if condition evaluates to False. Choose the correct option: a) Both A and R are true and R is the correct explanation of A. b) Both A and R are true but R is NOT the correct explanation of A. c) A is true but R is false. d) A is false but R is true.

Answers to Competency Based Questions

A1. 1 3 7 9 Explanation: The loop generates odd numbers from 1 to 9 (step of 2). When i is 5, the continue statement executes, skipping the print statement for that iteration.

A2. Logical Error: Ankush increments n (n = n + 1) instead of decrementing it. Because n starts at 10 and keeps increasing, the condition n > 0 will always be true, creating an infinite loop. Correction: Change n = n + 1 to n = n - 1.

A3.

n = int(input("Enter a positive integer: "))
factorial = 1

for i in range(1, n + 1):
    factorial *= i

print("Factorial of", n, "is", factorial)

A4. a) Both A and R are true and R is the correct explanation of A. The else block acts as an alternative execution path dependent entirely on the failure of an if block.