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:
- Read the first number from the user
- Read the second number from the user
- Calculate the difference (num1 − num2)
- 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 loops — while 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:
- The program asks the user to input their age.
- The condition
age >= 18is evaluated. - If the condition is True (age is 18 or more), the message "Eligible to vote" is printed.
- If the condition is False (age is less than 18), nothing happens — the program simply ends.
The
ifstatement 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
num1is greater thannum2, we subtractnum2fromnum1. - Otherwise, we subtract
num1fromnum2. - 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:
- First, the program checks if
number > 0. If True, it prints "Number is positive" and stops. - If False, it checks
number < 0. If True, it prints "Number is negative" and stops. - 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..elsestructure determines which operation to perform. - Inside the
"-"block, we have a nestedif..elseto ensure the difference is always positive. - Inside the
"/"block, we have a nestedif..elseto check ifval2is 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 ofif,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
ifstatement executes code only when a condition is True. - The
if..elsestatement chooses between two alternative paths. - The
if..elif..elsestatement evaluates multiple conditions in sequence and executes the first matching block. - Nested
ifstatements allow multi-level decision-making by placing oneifinside 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:
-
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.
-
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.
-
Nested blocks require deeper indentation: If you have an
ifstatement inside anotherifstatement (nested conditionals), the inner block must be indented further. -
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
