0% found this document useful (0 votes)
2 views13 pages

Python Control Flow Notes

This document provides comprehensive notes on Python control flow statements: break, continue, and pass, including their definitions, syntax, examples, and key rules. It explains how each statement alters the normal execution flow of a program, with practical examples for beginners to advanced users. Additionally, it includes a comparison table and memory tricks to help understand the differences and uses of these statements.

Uploaded by

stechnology741
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Python Control Flow Notes

This document provides comprehensive notes on Python control flow statements: break, continue, and pass, including their definitions, syntax, examples, and key rules. It explains how each statement alters the normal execution flow of a program, with practical examples for beginners to advanced users. Additionally, it includes a comparison table and memory tricks to help understand the differences and uses of these statements.

Uploaded by

stechnology741
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Control Flow

break | continue | pass

Complete Classroom Notes - Beginner to Advanced - 5 Examples Each Concept

Owner / Student: Subhashree Sahoo Subject: Python Programming | Class 12

Table of Contents
No. Topic

oo Location

1 Introduction to Control Flow

a h Page 1

S
2 break - Definition + 5 Examples (Beginner to Advanced) Page 2

e
3 continue - Definition + 5 Examples (Beginner to Advanced) Page 4

4 pass - Definition + 5 Examples (Beginner to Advanced)

r e Page 6

5 Comparison Table, Memory Tricks & Quick Q&A;

s h Page 8

h a
u b
S

Python Control Flow Notes | Subhashree Sahoo | Page 1


Introduction to Control Flow
What are jump / control statements and why do we need them?

In Python, a program normally runs line by line from top to bottom. But sometimes we need to skip some lines,
stop a loop early, or leave a block empty for later. This is where Control Flow Statements come in. Python
provides three such statements: break, continue, and pass. These are also called Jump Statements
because they change the normal execution order of a program.

Statement Colour Code What it does Loop Ends?

break RED Exits the loop immediately YES X

continue AMBER Skips current step, goes to next NO V

pass GREEN Does nothing - placeholder only

oo NO V

a h
S
e e
h r
a s
b h
S u

Python Control Flow Notes | Subhashree Sahoo | Page 2


break Statement
Exits the loop completely as soon as the condition is True

Definition
The break statement is used to terminate (exit) a loop immediately when a certain condition becomes True.
Once Python sees 'break', it stops executing the loop body and jumps to the first statement after the loop. It
works inside both for and while loops. Think of it as an emergency exit door - the moment you find it, you
leave the building (loop) right away, no matter how many floors (iterations) are remaining.

Syntax

for variable in sequence: if condition: break # code below break is skipped when break
triggers

oo
h
Example 1

Level: Beginner - Stop counting at 5

S a
We loop from 1 to 10. As soon as i reaches 5, break exits the loop. Numbers 6 to 10 are never printed because the loop ends
at 5.
for i in range(1, 11):
if i == 5:

e e
break
print(i)
print('Loop ended')
h r
Output:
1

a s
h
2
3
4
Loop ended

u b
Example 2
S
Level: Beginner+ - Search for a name in a list
We search through student names. The moment we find 'Riya', we stop. This saves time - we don't check remaining names
unnecessarily.
students = ['Aman', 'Priya', 'Riya', 'Rahul', 'Sunita']
for name in students:
if name == 'Riya':
print('Found Riya!')
break
print('Checking:', name)
Output:
Checking: Aman
Checking: Priya
Found Riya!

Python Control Flow Notes | Subhashree Sahoo | Page 3


Example 3

Level: Intermediate - Password validation with while loop


The program keeps asking for a password. If correct, break stops the loop. If wrong, it keeps asking. This is how real login
systems are designed.
correct = 'python123'
while True:
pwd = input('Enter password: ')
if pwd == correct:
print('Access Granted!')
break
print('Wrong! Try again.')
Output:
Wrong! Try again.
Wrong! Try again.
Access Granted!

Example 4

Level: Intermediate+ - Find first even number in a list


oo
algorithms.
a h
We loop through a list and break as soon as we find the first even number. This pattern is very common in data searching

numbers = [3, 7, 11, 4, 9, 2, 6]


for num in numbers:
S
if num % 2 == 0:
print('First even number:', num)

e e
r
break

h
Output:
First even number: 4

Example 5
a s
b h
Level: Advanced - Prime number checker (efficient algorithm)
We check if a number is prime by testing divisors from 2 to sqrt(n). The moment we find one divisor, we know it is NOT prime

import math
def is_prime(n):
S u
and break immediately. This avoids unnecessary calculations - a key technique for large numbers.

if n < 2: return False


for i in range(2, int([Link](n)) + 1):
if n % i == 0:
print(f'{n} NOT prime - divisor={i}')
break
else:
print(f'{n} IS prime')
is_prime(17)
is_prime(18)
Output:
17 IS prime
18 NOT prime - divisor=2

Key Rules for break

• break works ONLY inside for and while loops.

Python Control Flow Notes | Subhashree Sahoo | Page 4


• break exits ONLY the innermost loop when loops are nested.

• Code written AFTER break inside the loop body is never executed.

• Use break when you have found what you were looking for and want to stop.

• The for...else block does NOT execute if break was triggered.

oo
a h
S
e e
h r
a s
b h
S u

Python Control Flow Notes | Subhashree Sahoo | Page 5


continue Statement
Skips the current iteration and jumps to the next one

Definition
The continue statement is used to skip the rest of the current iteration of a loop and jump directly to the
next iteration. Unlike break (which ends the loop), continue does NOT end the loop - it just skips one step and
moves forward. Think of it like a skip button on a music playlist - you do not stop listening, you just skip one
song and the next one plays automatically.

Syntax

for variable in sequence: if condition: continue # this code is SKIPPED when condition is
True, but loop continues

oo
h
Example 1

Level: Beginner - Print only odd numbers

S a
We loop from 1 to 10. Whenever the number is even, we use continue to skip printing it. The loop keeps running but even
numbers are never printed.
for i in range(1, 11):
if i % 2 == 0:

e e
continue
print(i)
# Only odd numbers print

h r
Output:
1

a s
h
3
5
7
9

u b
Example 2
S
Level: Beginner+ - Skip absent students in attendance
We have a class roll. Students marked 'Absent' are skipped using continue. The loop does NOT stop - it continues and marks
all other students Present.
roll = ['Aman', 'Absent', 'Priya', 'Rahul', 'Absent', 'Sunita']
for student in roll:
if student == 'Absent':
continue
print('Present:', student)
Output:
Present: Aman
Present: Priya
Present: Rahul
Present: Sunita

Python Control Flow Notes | Subhashree Sahoo | Page 6


Example 3

Level: Intermediate - Skip negatives and sum positives


We have a mixed list. We skip all negatives using continue and add only positive numbers. This is a real data-cleaning
pattern used in data science and analytics.
numbers = [10, -3, 25, -7, 8, -1, 15, -9, 4]
total = 0
for n in numbers:
if n < 0:
continue
total += n
print('Sum of positives:', total)
Output:
Sum of positives: 62

Example 4

Level: Intermediate+ - Extract consonants from a name

oo
We take a name and print only its consonants (non-vowels) by skipping all vowels using continue. This teaches how continue

h
works with string character iteration.

a
word = 'Subhashree'
vowels = 'aeiouAEIOU'
result = ''
for ch in word:
S
if ch in vowels:
continue

e e
r
result += ch
print('Consonants only:', result)
Output:
Consonants only: Sbshr

s h
Example 5
h a
u b
Level: Advanced - Grade students, skip absent and failed
We have a dictionary of student marks. We skip absent students (None) and failures (below 35) using continue. Only valid

S
passing students receive a grade. This is a real-world school system pattern.
marks = {'Aman':78, 'Priya':None, 'Riya':45, 'Rahul':30, 'Sunita':91}
for name, score in [Link]():
if score is None:
print(f'{name}: Absent')
continue
if score < 35:
print(f'{name}: Failed')
continue
grade = 'A' if score>=75 else 'B' if score>=60 else 'C'
print(f'{name}: Grade {grade} ({score})')
Output:
Aman: Grade A (78)
Priya: Absent
Riya: Grade C (45)
Rahul: Failed
Sunita: Grade A (91)

Key Rules for continue

Python Control Flow Notes | Subhashree Sahoo | Page 7


• continue skips only the CURRENT iteration - the loop keeps running after.

• Code written AFTER continue in the same loop body is skipped for that step only.

• continue works in both for and while loops.

• Use continue to filter out unwanted or invalid data without stopping the loop.

• continue is NOT the same as break - break ends the loop, continue just skips one step.

oo
a h
S
e e
h r
a s
b h
S u

Python Control Flow Notes | Subhashree Sahoo | Page 8


pass Statement
A placeholder that does nothing - required when block cannot be left empty

Definition
The pass statement is a null operation - it literally does nothing when executed. Python requires that certain
blocks (if, for, while, def, class) cannot be left completely empty. If you want to leave a block empty for future
use, you MUST write pass inside it, otherwise Python will give an IndentationError. Think of pass as a
Coming Soon board on a shop - the shop exists and the board is there, but no product is ready yet. Key
difference from continue: pass does NOT skip to the next iteration - the loop continues normally after pass, just
as if nothing happened.

Syntax

for variable in sequence: if condition: pass # do nothing, loop continues normally # this
code runs normally after pass too

oo
Example 1
a h
Level: Beginner - pass in loop (note: 3 is still printed!)
S
completely different from continue.

e e
We loop 1 to 5. At i=3, we use pass. ALL numbers including 3 are still printed! This proves pass does nothing at all -

for i in range(1, 6):


if i == 3:

h r
s
pass
print(i)
# ALL 5 numbers print, including 3
Output:

h a
b
1
2
3
4
5

S u
Example 2

Level: Beginner+ - Empty function placeholder


When you plan a function but have not written code yet, use pass. Without pass, Python throws IndentationError. pass
solves this perfectly.
def calculate_marks():
pass # will write code later
def display_result():
pass # will write code later
print('Functions defined - no error!')
Output:
Functions defined - no error!

Python Control Flow Notes | Subhashree Sahoo | Page 9


Example 3

Level: Intermediate - Empty class blueprint


In object-oriented programming, you may want to define a class first and fill it later. pass allows you to create a valid, usable
class object with no methods yet.
class Student:
pass # will add attributes later
class Teacher:
pass
s = Student() # works fine!
t = Teacher() # works fine!
print(type(s))
Output:

Example 4

Level: Intermediate+ - Silent error handling with pass

error but takes no action - program continues.

oo
Sometimes we want to silently ignore a specific type of error and continue execution. pass inside an except block catches the

data = ['10', '20', 'abc', '30', 'xyz']


total = 0
for item in data:
a h
try:
total += int(item)
S
except ValueError:
pass # ignore bad non-numeric data

e e
print('Total:', total)
Output:
Total: 60
h r
Example 5
a s
b h
Level: Advanced - Full system skeleton with pass

u
In advanced Python, pass is used to define the entire skeleton of an application before coding. Here we design a Student
Management System structure. This is how professional developers plan large projects - define all classes and methods first,

S
implement them one by one later.
class StudentManagement:
def add_student(self):
pass
def delete_student(self):
pass
def update_marks(self):
pass
def generate_report(self):
pass
def send_notification(self):
pass
sms = StudentManagement()
print('System skeleton ready - no errors!')
Output:
System skeleton ready - no errors!

Key Rules for pass

Python Control Flow Notes | Subhashree Sahoo | Page 10


• pass does absolutely nothing - it is a no-operation (NOP) statement.

• Unlike continue, pass does NOT skip to the next iteration of a loop.

• pass is used as a placeholder in empty blocks: if, for, while, def, class.

• Without pass, an empty block causes an IndentationError in Python.

• pass is commonly used in top-down design and project planning stages.

oo
a h
S
e e
h r
a s
b h
S u

Python Control Flow Notes | Subhashree Sahoo | Page 11


Comparison Table & Memory Tricks
Quick revision reference for all three control flow statements

Full Comparison Table


Feature break continue pass

Purpose Exit loop immediately Skip current step only Do nothing (placeholder)

Loop stops? YES - exits completely NO - continues running NO - continues normally

Works inside for / while loops for / while loops Anywhere in Python

Remaining code in
iteration Skipped completely Skipped for that step Executes normally

Real-life analogy Emergency exit door Skip song button

oo Coming Soon board

Common use case Stop when target found Filter out bad data

a h Placeholder for future code

For...else behavior else block is SKIPPED else block runs

S else block runs

e e
Memory Tricks - Never Forget!

h r
B = BYE-BYE Loop!
a s
When you see break, the loop says BYE and exits completely. Use when your
job is done!

C = CHECK NEXT One!


b h When you see continue, skip this and CHECK the next item. Loop keeps going!

P = PENDING /
S u When you see pass, think 'This is PENDING - I will fill this block later.'
Placeholder!

Quick Q&A; Revision


Quick Questions & Answers

Q: Can break be used outside a loop? A: NO - it gives a SyntaxError.

Q: Does continue stop the loop? A: NO - it only skips the current one step.

Q: Is pass the same as writing nothing? A: YES - pass literally does nothing at runtime.

Q: What happens in nested loops with break? A: Only the INNERMOST loop is exited.

Q: Can we use all three in one program? A: YES - each serves a completely different purpose.

Python Control Flow Notes | Subhashree Sahoo | Page 12


Q: Will 3 print if we use pass when i==3? A: YES - pass does nothing, so 3 still prints.

These notes are prepared for Class 12 Python students. Owner: Subhashree Sahoo | All examples tested and verified in Python 3.x

oo
a h
S
e e
h r
a s
b h
S u

Python Control Flow Notes | Subhashree Sahoo | Page 13

You might also like