CBSE Class 11 Computer Science

Flow of Control

5 sections AI-powered notes
GET THE FULL EXPERIENCE

This is the chapter notes. Students get the interactive version.

  • Ask Aarav Sir anything — instant voice + chat doubts
  • Interactive lessons with audio narration + visual diagrams
  • Study Lab — paste any photo, PDF, or YouTube link to get it explained

Introduction

Introduction

When you wake up in the morning and get ready for school, you follow a routine — brush your teeth, get dressed, have breakfast, and leave for school. You perform these tasks one after another, in a specific order. This is exactly how a computer program executes by default: one instruction at a time, from top to bottom.

{{VISUAL: diagram: illustration of a bus following a single road with milestones labeled Statement 1, Statement 2, Statement 3, reaching a school building}}

In programming, this simple top-to-bottom execution is called sequential flow. Every Python program we've written so far has followed this pattern — the interpreter starts at the first line and marches straight through to the last line, executing each statement in the order it appears. Think of it like a bus carrying students to school along a single road with no turns or branches. The driver has no choice but to follow the road, milestone after milestone, until reaching the destination.

What is Flow of Control?

Flow of control refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. It's the roadmap that determines the path your program takes from start to finish.

{{KEY: type=definition | title=Flow of Control | text=The order of execution of statements in a program. It determines which statements run, in what sequence, and how many times.}}

In the simplest case — sequential execution — the flow of control is like a straight highway. But real-world problems rarely follow such simple paths. Imagine you're writing a program to check if a student passed an exam. You can't just execute statements blindly; you need to make decisions based on the marks entered. Or consider a program that prints numbers from 1 to 100 — you wouldn't want to write 100 separate print() statements! You need a way to repeat a block of code.

This is where control structures come into play. They allow us to alter the natural sequential flow and make our programs intelligent, flexible, and powerful.

Understanding Sequential Execution

Let's examine a simple program that calculates the difference between two numbers:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of", num1, "and", num2, "is", diff)

When you run this program, Python executes each line in order:

  1. Read the first number from the user
  2. Read the second number from the user
  3. Calculate the difference (num1 − num2)
  4. Display the result

{{VISUAL: diagram: flowchart showing four sequential boxes connected by downward arrows - Input num1, Input num2, Calculate diff, Print result}}

This works perfectly if num1 is greater than num2. But what if the user enters 5 as the first number and 7 as the second? The output would be −2 — a negative difference. For many applications (like calculating the distance between two points), we want the positive difference regardless of which number is larger.

To handle this, we need the program to make a decision: check which number is larger, then subtract the smaller from the larger. Sequential execution alone cannot achieve this — we need a way to choose between alternative paths based on a condition.

{{KEY: type=concept | title=Sequential Execution | text=The default mode where Python executes statements one after another in the order they appear in the code, from top to bottom, without skipping or repeating any statement.}}

Control Structures: The Two Pillars

To overcome the limitations of pure sequential flow, Python provides two fundamental types of control structures:

1. Selection (Decision Making)

Selection allows a program to choose between two or more alternative paths based on a condition. Think of it as a fork in the road — depending on certain criteria, you take one path or another.

In everyday life, we make selections constantly:

  • If it's raining, carry an umbrella; otherwise, don't
  • If you have ₹10, buy a pen; otherwise, save your money
  • If your marks are above 75, you get grade A; else if they're above 60, you get grade B; else, you get grade C

{{KEY: type=points | title=Characteristics of Selection | text=- Involves testing a condition that evaluates to True or False

  • Provides two or more alternative code paths
  • Only one path is executed based on the condition
  • Implemented using if, if..else, and if..elif..else statements in Python}}

2. Repetition (Looping)

Repetition allows a program to execute the same block of code multiple times. Instead of writing the same instructions over and over, we can tell Python to repeat them as long as a certain condition holds true or for a specific number of times.

Real-world examples of repetition:

  • Washing dishes: repeat the process of soap → scrub → rinse for each plate
  • Reading a chapter: repeat reading → understanding → note-making for each page
  • Counting sheep to fall asleep: repeat "one sheep, two sheep..." until you're sleepy

Repetition is implemented using loopswhile loops and for loops — which we'll explore in detail later in this chapter.

{{ZOOM: title=Why "Control" Structures? | text=They're called "control" structures because they give you — the programmer — control over the execution flow. Without them, you'd be stuck writing programs that can only march forward in a straight line, unable to make decisions or repeat actions. Control structures are what transform simple scripts into intelligent, responsive applications.}}

The Road Ahead

Understanding flow of control is fundamental to writing meaningful programs. Once you master selection and repetition, you'll be able to:

  • Build interactive programs that respond differently to different inputs
  • Validate user data and handle errors gracefully
  • Process large amounts of data efficiently using loops
  • Implement complex algorithms and logic
  • Create programs that solve real-world problems

In the sections that follow, we'll dive deep into selection using if, if..else, and if..elif..else statements. We'll learn how Python makes decisions, how to write conditions, and the critical concept of indentation that makes Python's syntax unique. Then we'll explore repetition through loops, and advanced topics like nested loops and loop control using break and continue statements.

{{KEY: type=exam | title=Common Exam Pattern | text=CBSE questions often ask you to trace the flow of control through a given program snippet, predict the output, or identify errors in if-else logic. Practice reading code carefully and mapping the execution path based on given inputs.}}


"The flow of control is the heartbeat of a program — it determines not just what the program does, but when and how it does it."


Selection

Selection

Introduction to Decision Making in Programs

In our daily lives, we constantly make decisions. When you visit a stationery shop with ₹10 to buy a pen, you must choose from various options. When you use a digital map to navigate, the app often shows multiple routes — shortest distance, least crowded, fastest — and you select the one that fits your priority. This concept of decision making is fundamental not just in real life, but also in programming.

In sequential execution (covered in the previous section), every statement runs one after another. But what if you want your program to choose between two or more paths based on certain conditions? This is where selection or conditional statements come into play.

Python implements decision-making through the if, if..else, and if..elif..else statements. These allow your program to evaluate a condition and execute different blocks of code depending on whether the condition is True or False.


The if Statement

The simplest form of selection is the if statement, which executes a block of code only if a specified condition is true.

{{KEY: type=definition | title=if Statement Syntax | text=An if statement evaluates a condition. If the condition is True, the indented block of code beneath it executes. If False, the block is skipped entirely.}}

Syntax:

if condition:
    statement(s)

Notice the colon (:) at the end of the if line and the indentation of the statement(s) below. Indentation is Python's way of grouping statements into a block — we'll discuss this in detail at the end of this page.

{{VISUAL: diagram: flowchart showing if statement flow with condition diamond, True arrow leading to statement block, and False arrow bypassing the block}}

Example: Checking Voting Eligibility

Let's write a program that checks if a user is eligible to vote. In India, the minimum voting age is 18.

age = int(input("Enter your age: "))
if age >= 18:
    print("Eligible to vote")

How it works:

  1. The program asks the user to input their age.
  2. The condition age >= 18 is evaluated.
  3. If the condition is True (age is 18 or more), the message "Eligible to vote" is printed.
  4. If the condition is False (age is less than 18), nothing happens — the program simply ends.

The if statement is like a gatekeeper — it only lets code through when the condition is satisfied.


The if..else Statement

Often, we want our program to take one of two paths — do something if a condition is true, and do something else if it is false. The if..else statement provides this capability.

{{KEY: type=definition | title=if..else Statement Syntax | text=An if..else statement evaluates a condition. If True, the first indented block executes. If False, the block under else executes. Exactly one of the two blocks will run.}}

Syntax:

if condition:
    statement(s)
else:
    statement(s)

{{VISUAL: diagram: flowchart showing if..else statement with condition diamond, True arrow leading to first block, False arrow leading to else block, both merging after execution}}

Example: Complete Voting Eligibility Check

Let's extend the previous example to inform users when they are not eligible to vote.

age = int(input("Enter your age: "))
if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

Now the program gives feedback in both cases. If the user is 18 or older, they see "Eligible to vote". Otherwise, they see "Not eligible to vote".

Real-World Application: Always Positive Difference

Recall Program 6-1 from the previous page, which calculated the difference between two numbers. If num1 was smaller than num2, the result was negative. Let's use if..else to always display a positive difference.

Program 6-2: Printing the Positive Difference of Two Numbers

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if num1 > num2:
    diff = num1 - num2
else:
    diff = num2 - num1

print("The difference of", num1, "and", num2, "is", diff)

Output:

Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1

How it works:

  • If num1 is greater than num2, we subtract num2 from num1.
  • Otherwise, we subtract num1 from num2.
  • This guarantees the result is always non-negative.

{{KEY: type=exam | title=Common Exam Pattern | text=Questions often ask you to modify a sequential program to include decision-making — e.g., "Modify the above program to display absolute difference." Always identify which variable/condition should drive the if..else split.}}


The if..elif..else Statement

Many real-world scenarios require checking multiple conditions. For example, a traffic signal can be red, orange, or green, and each colour demands a different action. Python provides the elif keyword (short for "else if") to chain multiple conditions.

{{KEY: type=definition | title=if..elif..else Statement Syntax | text=The if..elif..else statement evaluates conditions in sequence from top to bottom. As soon as one condition is True, its block executes and the entire if structure terminates. If no condition is True, the else block (if present) executes.}}

Syntax:

if condition1:
    statement(s)
elif condition2:
    statement(s)
elif condition3:
    statement(s)
else:
    statement(s)

You can have as many elif blocks as needed. The else block is optional.

{{VISUAL: diagram: flowchart showing if..elif..else with multiple condition diamonds in sequence, each with True arrow to its block and False arrow to next condition, final else block at the end}}

Example 1: Classifying a Number

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

if number > 0:
    print("Number is positive")
elif number < 0:
    print("Number is negative")
else:
    print("Number is zero")

How it works:

  1. First, the program checks if number > 0. If True, it prints "Number is positive" and stops.
  2. If False, it checks number < 0. If True, it prints "Number is negative" and stops.
  3. If both conditions are False, it prints "Number is zero".

Example 2: Traffic Signal

signal = input("Enter the colour: ")

if signal == "red" or signal == "RED":
    print("STOP")
elif signal == "orange" or signal == "ORANGE":
    print("Be Slow")
elif signal == "green" or signal == "GREEN":
    print("Go!")
else:
    print("Invalid signal colour")

This program checks the signal colour and displays the appropriate message. Notice the use of the or operator to handle both lowercase and uppercase input.

{{KEY: type=concept | title=Short-Circuit Evaluation | text=Python evaluates conditions from top to bottom and stops as soon as one is True. This is called short-circuit evaluation. Conditions that appear later are never checked if an earlier one succeeds, so order matters.}}


Nested if Statements

An if statement inside another if statement is called a nested if. This is useful when you need to check a condition only after another condition has already been satisfied.

Program 6-3: A Simple Four-Function Calculator

# Program to create a four-function calculator
result = 0
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter any one of the operator (+,-,*,/): ")

if op == "+":
    result = val1 + val2
elif op == "-":
    if val1 > val2:
        result = val1 - val2
    else:
        result = val2 - val1
elif op == "*":
    result = val1 * val2
elif op == "/":
    if val2 == 0:
        print("Error! Division by zero is not allowed. Program terminated")
    else:
        result = val1 / val2
else:
    print("Wrong input, program terminated")

print("The result is", result)

Output:

Enter value 1: 84
Enter value 2: 4
Enter any one of the operator (+,-,*,/): /
The result is 21.0

How it works:

  • The outer if..elif..else structure determines which operation to perform.
  • Inside the "-" block, we have a nested if..else to ensure the difference is always positive.
  • Inside the "/" block, we have a nested if..else to check if val2 is zero, preventing division by zero.

{{KEY: type=points | title=Key Points on Nested if | text=- Nested if statements allow multiple levels of decision-making.

  • Each nested if must be properly indented to show its parent-child relationship.
  • Use nested if when the inner condition is meaningful only after the outer condition is True.
  • Avoid excessive nesting (more than 2-3 levels) as it reduces code readability.}}

{{ZOOM: title=Why Not Use Multiple Separate if Statements? | text=If you write multiple separate if statements instead of elif, every single if will be checked even after one condition is True. This wastes computation and can lead to unexpected behaviour if conditions overlap. The elif chain stops as soon as one condition succeeds — it is both more efficient and logically clearer.}}


The Role of Indentation in Python

Most programming languages use curly braces {} to group statements into blocks. Python, however, uses indentation — the number of spaces or tabs at the beginning of a line. This makes Python code visually clean and forces programmers to write readable code.

{{KEY: type=concept | title=Indentation in Python | text=Indentation is the whitespace at the beginning of a line. In Python, it defines code blocks — statements with the same indentation level belong to the same block. Mixing tabs and spaces or inconsistent indentation will cause an IndentationError.}}

Rules for Indentation:

  • Use 4 spaces per indentation level (recommended by PEP 8, Python's style guide).
  • All statements within the same block must have the same indentation.
  • Do not mix tabs and spaces — choose one and stick to it.
  • The colon : at the end of if, elif, else, for, while, and function definitions signals that an indented block follows.

Example:

if age >= 18:
    print("You are an adult")      # 4 spaces
    print("You can vote")          # 4 spaces
print("Thank you")                 # No indentation — outside the if block

The first two print() statements are inside the if block because they are indented. The third print() is outside the block and will execute regardless of the condition.

{{KEY: type=exam | title=Common Mistake in Exams | text=Incorrect or inconsistent indentation is one of the most frequent errors students make while writing code in exams. Always count your spaces carefully and align statements properly. Even one extra or missing space can break your code.}}


Summary

In this page, we explored how programs make decisions using selection statements:

  • The if statement executes code only when a condition is True.
  • The if..else statement chooses between two alternative paths.
  • The if..elif..else statement evaluates multiple conditions in sequence and executes the first matching block.
  • Nested if statements allow multi-level decision-making by placing one if inside another.
  • Indentation is Python's way of defining code blocks — it is not optional but a core part of the language syntax.

These tools allow you to write programs that react intelligently to different inputs and situations — the foundation of all meaningful software.


Indentation

Indentation

In most programming languages, blocks of code are defined using curly braces { } or special keywords like begin and end. Python takes a completely different approach — it uses indentation (leading whitespace at the beginning of a line) to define the structure and scope of code blocks. This is not just a stylistic choice; it is a syntactic requirement that determines how your program executes.

Understanding and mastering indentation is critical for writing correct Python programs. A single misplaced space or tab can change the meaning of your code entirely, or worse, cause a syntax error that prevents your program from running at all.


What is Indentation?

Indentation refers to the spaces or tabs placed at the beginning of a line of code. In Python, the amount of indentation determines which statements belong to the same block and which statements are controlled by structures like if, elif, else, for, and while.

{{KEY: type=definition | title=Indentation | text=Leading whitespace (spaces or tabs) at the beginning of a statement that determines the grouping of statements into code blocks in Python.}}

Consider the following example from Program 6-4 in the NCERT text:

num1 = 5
num2 = 6
if num1 > num2:      # Block 1 starts
    print("first number is larger")
    print("Bye")
else:                # Block 2 starts
    print("second number is larger")
    print("Bye Bye")

Here, the two print() statements under the if condition are indented by the same amount (typically four spaces or one tab). This tells Python that both statements belong to the same block and should only execute when num1 > num2 is True. Similarly, the two statements under else form their own block.

{{VISUAL: diagram: side-by-side comparison showing Python code with indentation on the left and equivalent C code with curly braces on the right, highlighting how indentation replaces braces}}


Rules for Proper Indentation

Python's interpreter is extremely strict about indentation. Even a single extra space can lead to an IndentationError. To write error-free Python code, follow these rules:

  1. Use consistent spacing: All statements in the same block must be indented by the same number of spaces or tabs. Mixing spaces and tabs in the same block will cause errors.

  2. Standard practice: The Python community recommends using four spaces for each level of indentation. Most modern code editors automatically insert four spaces when you press the Tab key.

  3. Nested blocks require deeper indentation: If you have an if statement inside another if statement (nested conditionals), the inner block must be indented further.

  4. No indentation for top-level code: Statements that are not inside any block (like variable declarations at the start of a program) should have zero indentation.

{{KEY: type=points | title=Indentation Best Practices | text=- Use four spaces per indentation level (Python standard).

  • Never mix tabs and spaces in the same program.
  • Ensure all statements in a block have identical indentation.
  • Use a code editor that shows whitespace characters for debugging.}}

{{VISUAL: diagram: visual representation of nested indentation levels showing outer if block, inner if block, and innermost statement with increasing left margins marked as 0, 4, and 8 spaces}}


Indentation in Nested Structures

When you have control structures inside other control structures — such as an if inside another if, or a loop inside a conditional — each additional level requires one more level of indentation.

Let's revisit the calculator example from the NCERT text. The program checks which operator the user has entered and performs the corresponding calculation:

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

if operator == '+':
    print(num1 + num2)
elif operator == '-':
    if num2 > num1:                    # Nested if
        print(num2 - num1)
    else:                              # Nested else
        print(num1 - num2)
elif operator == '*':
    print(num1 * num2)
elif operator == '/':
    if num2 != 0:                      # Nested if
        print(num1 / num2)
    else:                              # Nested else
        print("Cannot divide by zero")
else:
    print("Invalid operator")

Notice how the nested if..else blocks (inside the elif for - and /) are indented one level deeper than the outer elif statements. This visual hierarchy makes it clear which conditions are dependent on others.

{{KEY: type=concept | title=Nested Indentation | text=When control structures are nested inside one another, each inner level must be indented one step further than its parent. This creates a visual and logical hierarchy that Python uses to group statements correctly.}}


Common Indentation Errors

Even experienced programmers occasionally make indentation mistakes. Here are the most common pitfalls:

Error 1: Inconsistent Indentation

if num > 0:
    print("Positive")
      print("Greater than zero")  # Extra spaces — Error!

Result: IndentationError: unexpected indent

Error 2: Missing Indentation

if num > 0:
print("Positive")  # Should be indented — Error!

Result: IndentationError: expected an indented block

Error 3: Mixing Tabs and Spaces

if num > 0:
    print("Line 1")  # Four spaces
	print("Line 2")  # One tab — looks same but Error!

Result: TabError: inconsistent use of tabs and spaces in indentation

Stuck on something here?
Aarav Sir explains any part — voice or chat — 24/7.

{{KEY: type=exam | title=Exam Alert | text=CBSE exam questions often include code snippets with intentional indentation errors. Always trace which statements belong to which block before answering questions on output or debugging.}}

{{VISUAL: diagram: three code snippets labeled Error 1, Error 2, Error 3 with red underlines showing the exact location and nature of each indentation error}}


Why Indentation Matters

Indentation is not just a cosmetic feature — it defines the logic of your program. Consider this example:

Version 1:

if temperature > 30:
    print("It's hot")
    print("Drink water")
print("Stay healthy")

Output (if temperature = 35):

It's hot
Drink water
Stay healthy

Version 2:

if temperature > 30:
    print("It's hot")
print("Drink water")
print("Stay healthy")

Output (if temperature = 35):

It's hot
Drink water
Stay healthy

In Version 1, both "Drink water" and "Stay healthy" are printed regardless of the temperature. In Version 2, only "Drink water" and "Stay healthy" print always — but "It's hot" prints only when the condition is true. The difference? One level of indentation.

{{ZOOM: title=Why Python chose indentation | text=Python's creator, Guido van Rossum, made indentation mandatory to improve code readability. Since programmers naturally indent code to show structure, Python enforces this as syntax — making "readable code" and "correct code" the same thing.}}


Practical Tips for Managing Indentation

  • Use a good code editor: Tools like IDLE, PyCharm, VS Code, and Thonny automatically manage indentation and highlight errors.
  • Enable "show whitespace": Most editors can display dots for spaces and arrows for tabs, making it easy to spot inconsistencies.
  • Stick to one style: Choose either spaces or tabs for your entire project and never mix them.
  • Check your code block-by-block: When debugging, verify that every if, elif, else, for, and while has the correct indented block beneath it.

Remember: In Python, indentation is not optional — it is the language's way of understanding your intent.


Repetition

Repetition

In everyday life, we repeatedly perform tasks — waking up at the same time each morning, brushing our teeth, watering plants, or checking our phone for messages. Similarly, many natural and computational processes involve iteration, where a sequence of steps is executed over and over again until a specific condition is met. In programming, this repetitive execution of a block of code is called a loop, and it is a fundamental pillar of control flow that allows us to write efficient, concise, and powerful programs.


6.4 Understanding Iteration

Iteration refers to the process of repeating a set of instructions multiple times. Imagine the life cycle of a butterfly: it lays eggs, the eggs hatch into caterpillars, the caterpillars become pupae, and finally, adult butterflies emerge — only to lay eggs again and restart the cycle. This natural repetition is a perfect example of iteration.

{{VISUAL: diagram: the four-stage life cycle of a butterfly showing egg, caterpillar, pupa, and butterfly in a circular loop with arrows indicating repetition}}

In programming, iteration allows us to execute a block of statements repeatedly based on a control condition. Instead of writing the same code hundreds or thousands of times, we define the logic once and let the loop handle the repetition. This makes our code shorter, more readable, and easier to maintain.

{{KEY: type=definition | title=Iteration | text=Iteration is the repeated execution of a set of statements in a program as long as a specified condition remains true. It is implemented using looping constructs like for and while.}}

Why Use Loops?

Consider the task of printing the first five natural numbers. We could write:

print(1)
print(2)
print(3)
print(4)
print(5)

This works fine for five numbers. But what if we need to print the first 100,000 natural numbers? Writing 100,000 print() statements is impractical, error-prone, and inefficient. A loop solves this problem elegantly:

  1. Initialize a variable (e.g., count = 1).
  2. Print the current value of count.
  3. Increment count by 1.
  4. Repeat steps 2 and 3 as long as count <= 100000.

This logic condenses what would have been 100,000 lines of code into just a few statements, demonstrating the power of iteration.

{{KEY: type=concept | title=Loop Control Condition | text=A loop executes as long as its control condition evaluates to True. This condition is checked before or during each iteration. When the condition becomes False, the loop terminates, and control passes to the next statement in the program. The programmer must ensure that the condition eventually becomes False to avoid infinite loops.}}


6.4.1 The 'For' Loop

The for loop is used when we know in advance how many times we want to repeat a block of code, or when we want to iterate over a specific sequence of values (such as a range of numbers, characters in a string, or items in a list). The for loop assigns each value in the sequence to a control variable and executes the loop body for that value. Once all values have been processed, the loop terminates automatically.

{{VISUAL: diagram: flowchart of a for loop showing initialization of control variable, condition check, execution of loop body, increment of control variable, and exit when condition is false}}

Syntax of the For Loop

for <control-variable> in <sequence/items in range>:
    <statements inside body of the loop>
  • Control variable: Holds the current value from the sequence during each iteration.
  • Sequence: A collection of values (e.g., characters in a string, numbers in a range).
  • Body: The indented block of code executed once per iteration.

Example: Iterating Over a String

#Program 6-6
#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
    print(letter)

Output:

P
Y
T
H
O
N

Here, the variable letter takes on each character of the string 'PYTHON' in turn, and the print() statement is executed six times.

Example: Iterating Over a List

#Program 6-7
#Print the given sequence of numbers using for loop
count = [10, 20, 30, 40, 50]
for num in count:
    print(num)

Output:

10
20
30
40
50

Each element of the list count is assigned to num one at a time, and the loop body prints that value.

{{KEY: type=points | title=Key Features of For Loop | text=- The number of iterations is determined in advance by the sequence or range.

  • The control variable automatically takes on each value in the sequence.
  • The loop body must be indented consistently.
  • Once all values are exhausted, the loop terminates and control moves to the next statement.}}

Example: Filtering Even Numbers

#Program 6-8
#Print even numbers in the given sequence
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if (num % 2) == 0:
        print(num, 'is an even Number')

Output:

2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number

Notice how the if statement inside the loop provides selective execution — only even numbers are printed. This combines both branching and iteration.


The range() Function

The range() function is a powerful built-in tool in Python that generates a sequence of integers. It is commonly used with for loops to control the number of iterations.

Syntax

range([start], stop[, step])
  • start (optional): The first value in the sequence (default is 0).
  • stop (required): The sequence stops before this value (exclusive).
  • step (optional): The difference between consecutive values (default is 1).

All parameters must be integers. The step can be positive or negative, but not zero.

{{KEY: type=definition | title=range() Function | text=The range() function generates a sequence of integers starting from a given start value (default 0) up to but not including the stop value, with increments of a given step (default 1). It is commonly used in for loops to iterate a specific number of times.}}

Examples of range()

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]

>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]

In the last example, a negative step produces a decreasing sequence.

Using range() in a Loop

#Program 6-9
#Print multiples of 10 for numbers in a given range
for num in range(5):
    if num > 0:
        print(num * 10)

Output:

10
20
30
40

Here, range(5) generates [0, 1, 2, 3, 4], but we skip 0 with the if condition and print multiples of 10 for the rest.

{{KEY: type=exam | title=Common Mistake with range() | text=Remember that range(stop) excludes the stop value. If you write range(10), the sequence is [0, 1, ..., 9], NOT [0, 1, ..., 10]. This is a frequent source of off-by-one errors in exams.}}


6.4.2 The 'While' Loop

The while loop is used when the number of iterations is not known in advance and depends on a condition being tested repeatedly. The loop continues to execute as long as the control condition remains True. Before each iteration, the condition is evaluated; if it is True, the loop body executes. If it is False, the loop terminates immediately.

{{VISUAL: diagram: flowchart of a while loop showing initialization, condition check, execution of loop body, update of control variable, and exit when condition becomes false}}

Syntax of the While Loop

<initialization statement>
while <control condition>:
    <statements inside body of the loop>
    <update control variable>
  • Initialization: Set the control variable before the loop.
  • Control condition: Checked before each iteration; must eventually become False.
  • Update: Modify the control variable inside the loop to progress toward termination.

{{ZOOM: title=Infinite Loops and Exit Conditions | text=A while loop without a proper update to its control variable can run forever, creating an infinite loop. Always ensure that the loop's condition will eventually become False. For example, if you forget to increment a counter variable, the loop will never terminate.}}

{{KEY: type=concept | title=While Loop Characteristics | text=The while loop is ideal when the number of iterations depends on dynamic conditions (e.g., user input, sensor readings, or convergence criteria). The loop tests the condition BEFORE each iteration, so if the condition is False at the start, the loop body may never execute at all.}}

In iteration, the key is not just repeating — it's repeating with purpose until a goal is achieved.


By mastering both for and while loops, you gain the ability to automate repetitive tasks, process large datasets, and implement complex algorithms efficiently. In the next section, we will explore the while loop in greater depth and learn how to combine loops with conditional logic to solve real-world problems.


The ‘For’ Loop

The 'For' Loop

When you need to repeat a block of code a specific number of times, or iterate through a collection of items one by one, the for loop is your go-to tool. Unlike the while loop, which depends on a condition that may or may not become false, the for loop is designed to work with a known sequence of values. This makes it the natural choice when you know in advance how many times the loop should execute, or when you want to process each element in a collection.


Understanding the For Loop

The for loop in Python is used to iterate over a sequence. A sequence can be a range of numbers, the characters in a string, elements in a list, or items in other data types like tuples and dictionaries (which we will explore in later chapters). With each iteration, the loop picks the next item from the sequence and executes the statements in its body.

The key feature of the for loop is the control variable. This variable automatically takes on the value of each item in the sequence, one at a time, until all items have been processed. Once the sequence is exhausted, the loop terminates, and the program continues with the statement immediately following the loop.

{{VISUAL: diagram: flowchart showing the execution flow of a for loop with control variable, sequence, loop body, and exit condition}}

{{KEY: type=definition | title=For Loop | text=A for loop is a looping construct that iterates over a sequence of values or items. It executes a block of code repeatedly for each element in the sequence, and terminates automatically when all elements have been processed.}}

Syntax of the For Loop

The general syntax of a for loop in Python is:

for <control-variable> in <sequence/items in range>:
    <statements inside body of the loop>
  • control-variable: A variable that takes on the value of each item in the sequence, one at a time.
  • sequence/items in range: The collection of values over which the loop iterates (e.g., a string, a list, or a range of numbers).
  • statements inside body of the loop: The code block that executes for each item. This block must be indented.

{{KEY: type=points | title=Key Features of For Loop | text=- The number of iterations is determined by the length of the sequence.

  • The control variable automatically updates with each iteration.
  • The loop body must be indented with respect to the for statement.
  • The loop terminates automatically when the sequence is exhausted.}}

Iterating Over Sequences

Let's see how the for loop works in practice by iterating over different types of sequences.

Iterating Over a String

Strings are sequences of characters. When you use a for loop with a string, the control variable takes on each character one by one.

Program 6-6: Print the characters in the string 'PYTHON' using a for loop.

#Program 6-6
#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
    print(letter)

Output:

P
Y
T
H
O
N

In this example, the control variable letter takes on each character in the string 'PYTHON' — first 'P', then 'Y', and so on. The print() statement executes six times, once for each character.

Iterating Over a List

A list is a collection of values enclosed in square brackets. We will study lists in detail in a later chapter, but for now, understand that a list can contain numbers, strings, or other data types.

Program 6-7: Print the numbers in a given sequence using a for loop.

#Program 6-7
#Print the given sequence of numbers using for loop
count = [10, 20, 30, 40, 50]
for num in count:
    print(num)

Output:

10
20
30
40
50

Here, the list count contains five integers. The control variable num takes on each value in turn, and the loop executes five times.

Combining For Loop with Conditional Statements

You can nest conditional statements inside a for loop to perform selective operations on items in the sequence.

Program 6-8: Print even numbers in a given sequence using a for loop.

#Program 6-8
#Print even numbers in the given sequence
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if (num % 2) == 0:
        print(num, 'is an even Number')

Output:

2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number

Notice how the if statement is indented with respect to the for statement, and the print() statement is indented further with respect to the if. This nested indentation is crucial in Python — it defines the structure and scope of your code.

{{KEY: type=exam | title=Common Exam Pattern | text=CBSE exams frequently ask you to write programs using for loops combined with if-else statements to filter or process specific items from a sequence. Practice tracing loop execution step-by-step on paper.}}


The range() Function

While iterating over existing sequences like strings and lists is useful, you often need to generate a sequence of numbers on the fly. Python provides the range() function for this purpose.

{{VISUAL: diagram: illustration of range function showing start, stop, and step parameters with example sequences generated}}

Syntax of range()

range([start], stop[, step])

The range() function creates a sequence of integers from start to stop (excluding stop), incrementing by step at each iteration.

  • start (optional): The starting value of the sequence. Default is 0.
  • stop (required): The ending value of the sequence (this value is not included).
  • step (optional): The difference between consecutive values. Default is 1.

{{KEY: type=definition | title=Range Function | text=The range() function is a built-in Python function that generates a sequence of integers. It takes three parameters: start (optional, default 0), stop (required, not included), and step (optional, default 1). All parameters must be integers.}}

Using range() — Examples

Let's explore how range() works with different parameter combinations.

Example 6.4:

# start and step not specified
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# default step value is 1
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]

# step value is 5
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

# step value is -1. Hence, decreasing sequence is generated
>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]

Key observations:

  • range(10) generates integers from 0 to 9 (stop value 10 is excluded).
  • range(2, 10) starts at 2 and stops before 10.
  • range(0, 30, 5) increments by 5 each time: 0, 5, 10, 15, 20, 25.
  • range(0, -9, -1) uses a negative step to create a descending sequence.

{{KEY: type=concept | title=Stop Value Exclusion | text=The stop parameter in range() is always excluded from the generated sequence. If you write range(1, 6), you get [1, 2, 3, 4, 5], not [1, 2, 3, 4, 5, 6]. This behavior is consistent across Python and helps avoid off-by-one errors.}}

Using range() in For Loops

The range() function is most commonly used with for loops to repeat a block of code a specific number of times.

Program 6-9: Print the multiples of 10 for numbers in a given range.

#Program 6-9
#Print multiples of 10 for numbers in a given range
for num in range(5):
    if num > 0:
        print(num * 10)

Output:

10
20
30
40

Here's what happens step-by-step:

  1. range(5) generates the sequence [0, 1, 2, 3, 4].
  2. The control variable num takes on each value in turn.
  3. The if condition filters out 0 (since 0 > 0 is False).
  4. For num = 1, 2, 3, 4, the program prints num * 10.

{{ZOOM: title=Why range() returns a range object, not a list | text=Technically, range() does not return a list — it returns a special range object that generates values on demand (lazily). This saves memory, especially for large sequences. We use list(range()) in examples to display the full sequence, but in loops, you can use range() directly without converting it to a list.}}


Practical Applications of For Loops

Counting and Accumulation

You can use a for loop to calculate sums, products, or counts. For example, summing the first 10 natural numbers:

total = 0
for num in range(1, 11):
    total += num
print("Sum of first 10 natural numbers:", total)

Output:

Sum of first 10 natural numbers: 55

Pattern Printing

for loops are excellent for printing patterns, tables, and repetitive structures:

for i in range(1, 6):
    print('*' * i)

Output:

*
**
***
****
*****

Real-World Example: Calculating Compound Interest

Suppose you want to calculate the growth of an investment over multiple years using compound interest.

principal = 10000
rate = 0.05  # 5% annual interest
years = 5

for year in range(1, years + 1):
    principal = principal * (1 + rate)
    print(f"Year {year}: ₹{principal:.2f}")

This loop repeats the compound interest calculation for each year, updating and displaying the principal after each iteration.

{{VISUAL: chart: table showing iteration number, control variable value, and output for a sample for loop}}

{{KEY: type=exam | title=Tracing Loop Execution | text=CBSE exams often include dry-run or trace-table questions where you must manually execute a loop and record variable values after each iteration. Practice creating trace tables for nested loops and loops with conditionals.}}


Summary

The for loop is a powerful and elegant construct for iterating over sequences. Its automatic iteration and built-in termination make it safer and more predictable than while loops for many common tasks. The range() function complements the for loop perfectly, allowing you to generate numeric sequences with fine control over start, stop, and step values.

Key Takeaway: Use a for loop when you know the number of iterations in advance or when you need to process each element in a collection. Combine it with range() for numeric sequences and with conditional statements for selective processing.

In the next section, we will explore how to control loop execution even more precisely using the break and continue statements, which let you exit loops early or skip specific iterations.

In this chapter

  • 1.Introduction
  • 2.Selection
  • 3.Indentation
  • 4.Repetition
  • 5.The ‘For’ Loop

Frequently asked questions

What is Introduction?

When you wake up in the morning and get ready for school, you follow a routine — brush your teeth, get dressed, have breakfast, and leave for school. You perform these tasks **one after another**, in a specific order. This is exactly how a computer program executes by default: one instruction at a time, from top to bot

What is Selection?

In our daily lives, we constantly make decisions. When you visit a stationery shop with ₹10 to buy a pen, you must **choose** from various options. When you use a digital map to navigate, the app often shows multiple routes — shortest distance, least crowded, fastest — and you **select** the one that fits your priority

What is Indentation?

In most programming languages, blocks of code are defined using curly braces `{ }` or special keywords like `begin` and `end`. **Python takes a completely different approach** — it uses **indentation** (leading whitespace at the beginning of a line) to define the structure and scope of code blocks. This is not just a s

What is Repetition?

In everyday life, we repeatedly perform tasks — waking up at the same time each morning, brushing our teeth, watering plants, or checking our phone for messages. Similarly, many natural and computational processes involve **iteration**, where a sequence of steps is executed over and over again until a specific conditio

What is The ‘For’ Loop?

When you need to repeat a block of code a specific number of times, or iterate through a collection of items one by one, the **for loop** is your go-to tool. Unlike the `while` loop, which depends on a condition that may or may not become false, the **for loop** is designed to work with a *known sequence* of values. Th

More chapters in CBSE Class 11 Computer Science

Want the full CBSE Class 11 Computer Science experience?

Every chapter. Interactive lessons. AI teacher on tap. Study Lab for any photo or PDF. 3-day free trial — no credit card.

1000s of students
100% NCERT-aligned
Powered by AI

Install Learn Skill

Add to home screen for the best experience