Total Pageviews

Wednesday, September 9, 2026

algorithms,

```html

🐍 ALGORITHM

Definition • Characteristics • Steps • Examples • Advantages

1. What is an Algorithm?

An Algorithm is a finite sequence of well-defined and unambiguous steps used to solve a particular problem or perform a specific task.

An algorithm describes what should be done step by step before the actual Python program is written.

Simple Idea:
Problem → Algorithm → Flowchart → Python Program → Output

2. Characteristics of an Algorithm

1️⃣

Input

An algorithm may accept zero or more inputs.

2️⃣

Output

It should produce at least one meaningful result.

3️⃣

Definiteness

Every step must be clear and unambiguous.

4️⃣

Finiteness

The algorithm must terminate after a finite number of steps.

5️⃣

Effectiveness

Each step must be simple enough to be carried out.

6️⃣

Generality

It should solve a class of similar problems rather than only one particular input.

3. Steps for Writing an Algorithm

  1. Understand the Problem
    Clearly identify what the problem is asking.
  2. Identify Inputs
    Determine what data is required.
  3. Identify Output
    Determine what result must be produced.
  4. Develop the Logic
    Decide the operations and decisions required.
  5. Write the Steps
    Arrange the operations in the correct sequence.
  6. Check the Algorithm
    Test the steps using sample data.
  7. Convert into Program
    Implement the algorithm using Python or another programming language.

4. Example 1 – Addition of Two Numbers

Problem

Write an algorithm to add two numbers.

Algorithm

  1. Start.
  2. Input the first number A.
  3. Input the second number B.
  4. Calculate SUM = A + B.
  5. Display SUM.
  6. Stop.

Python Program

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

sum = a + b

print("Sum =", sum)

Output

Enter first number: 10 Enter second number: 20 Sum = 30

5. Example 2 – Find the Largest of Two Numbers

Algorithm

  1. Start.
  2. Input A and B.
  3. Compare A and B.
  4. If A is greater than B, display A.
  5. Otherwise, display B.
  6. Stop.

Python Program

a = int(input("Enter A: "))
b = int(input("Enter B: "))

if a > b:
    print("Largest =", a)
else:
    print("Largest =", b)

Output

Enter A: 45 Enter B: 30 Largest = 45

6. Example 3 – Check Even or Odd

Algorithm

  1. Start.
  2. Input a number N.
  3. Calculate N % 2.
  4. If the remainder is 0, display Even.
  5. Otherwise, display Odd.
  6. Stop.

Python Program

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

if n % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")

Output

Enter a number: 18 Even Number

7. Example 4 – Calculate Factorial

Algorithm

  1. Start.
  2. Input N.
  3. Set FACT = 1.
  4. Repeat from 1 to N.
  5. Multiply FACT by the current number.
  6. Display FACT.
  7. Stop.

Python Program

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

fact = 1

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

print("Factorial =", fact)

Output

Enter a number: 5 Factorial = 120

8. Algorithm vs Program

Algorithm Program
Step-by-step solution to a problem. Actual implementation of the solution.
Usually written in simple language. Written using a programming language.
Language independent. Language dependent.
Focuses on logic. Focuses on executable instructions.
Can be converted into different programs. Runs according to a particular language environment.

9. Algorithm vs Flowchart

Algorithm Flowchart
Written step-by-step procedure. Graphical representation of the procedure.
Uses statements or natural language. Uses standard symbols.
Easy to modify. Modification may require redrawing.
Good for detailed steps. Good for visual understanding.
Does not require graphical symbols. Requires standard graphical symbols and arrows.

10. Advantages of Algorithm

✅ Advantages

  • Easy to understand.
  • Provides a clear solution strategy.
  • Helps in program planning.
  • Language independent.
  • Easy to test using sample data.
  • Helps identify logical errors.
  • Useful before writing actual code.
  • Acts as documentation.
  • Makes complex problems easier to break into steps.
  • Can be converted into a flowchart or program.

❌ Disadvantages

  • Complex problems may require lengthy algorithms.
  • Writing detailed algorithms can be time-consuming.
  • It does not directly execute on a computer.
  • Different programmers may describe the same logic differently.
  • Very detailed algorithms may become difficult to read.
  • Frequent changes may require rewriting several steps.

11. Rules for Writing a Good Algorithm

  1. Start with a clear first step.
  2. Use simple and understandable language.
  3. Each step should have a clear meaning.
  4. Avoid ambiguous statements.
  5. Maintain the correct sequence of operations.
  6. Clearly identify input and output.
  7. Ensure that the algorithm terminates.
  8. Test the algorithm with sample values.
  9. Use meaningful variable names.
  10. Keep unnecessary steps out of the algorithm.

12. Important Points for Examination

  • An algorithm is a finite sequence of well-defined steps used to solve a problem.
  • The five important characteristics are input, output, definiteness, finiteness and effectiveness.
  • Algorithms are generally language independent.
  • An algorithm describes the logic before coding.
  • Algorithms can be represented using flowcharts.
  • A good algorithm should be clear, finite and effective.
  • Every step should be unambiguous.

13. Quick Summary

Algorithm = A finite sequence of clear and well-defined steps used to solve a problem.

Characteristics:
Input → Output → Definiteness → Finiteness → Effectiveness

Program Development:
Problem → Algorithm → Flowchart → Python Code → Output

A well-designed algorithm makes programming easier, reduces logical errors and provides a clear roadmap for implementation.
```

decision table,

```html

🐍 Decision Table

Definition • Structure • Rules • Examples • Python Implementation

1. What is a Decision Table?

A Decision Table is a tabular method used to represent different conditions and the actions that should be performed for each possible combination of conditions.

It is especially useful when a problem contains multiple conditions and multiple possible actions.

Simple Idea:
Conditions → Rules → Actions

2. Main Components of a Decision Table

1

Conditions

Conditions are the questions or situations that must be evaluated.

Example: Age ≥ 18?
2

Condition Entries

These indicate whether a condition is True, False, Yes, or No.

3

Actions

Actions are the operations performed when conditions are satisfied.

4

Rules

Each column generally represents one possible combination of conditions and its corresponding action.

3. General Structure of a Decision Table

Conditions
Condition 1 Y Y N
Condition 2 Y N Y
Actions
Action 1
Action 2

Here Y = Yes/True and N = No/False.

4. Example – Student Pass or Fail

Problem

A student passes if the marks are greater than or equal to 40. Otherwise, the student fails.

Decision Table

Condition / Action Rule 1 Rule 2
Marks ≥ 40? Yes No
Display "PASS"
Display "FAIL"

Python Program

marks = int(input("Enter marks: "))

if marks >= 40:
    print("PASS")
else:
    print("FAIL")

Output

Enter marks: 65 PASS

5. Example – Login System

Consider a login system with two conditions:

  • Username is correct.
  • Password is correct.

Decision Table

Condition / Action Rule 1 Rule 2 Rule 3 Rule 4
Username Correct? Yes Yes No No
Password Correct? Yes No Yes No
Login Successful
Login Failed

Python Implementation

username = input("Username: ")
password = input("Password: ")

if username == "admin" and password == "1234":
    print("Login Successful")
else:
    print("Login Failed")

Output

Username: admin Password: 1234 Login Successful

6. Example – Discount Calculation

Suppose a shop provides a discount based on purchase amount.

Condition / Action Rule 1 Rule 2 Rule 3
Amount ≥ 5000? Yes No No
Amount ≥ 2000? Yes No
20% Discount
10% Discount
No Discount

Python Program

amount = float(input("Enter purchase amount: "))

if amount >= 5000:
    discount = amount * 0.20
elif amount >= 2000:
    discount = amount * 0.10
else:
    discount = 0

final_amount = amount - discount

print("Discount =", discount)
print("Final Amount =", final_amount)

7. Advantages of Decision Tables

✅ Advantages

  • Easy to understand.
  • Clearly represents multiple conditions.
  • Helps identify missing combinations.
  • Reduces logical errors.
  • Useful for complex decision-making problems.
  • Helps programmers design conditional statements.
  • Useful for testing and test-case generation.
  • Provides clear documentation.
  • Easy to compare different rules.

❌ Disadvantages

  • Large numbers of conditions can create large tables.
  • Tables can become difficult to read.
  • Creating all possible combinations may be time-consuming.
  • Not ideal for simple sequential problems.
  • Complex actions may require additional explanation.
  • Frequent changes may require table modification.

8. Decision Table vs Flowchart

Decision Table Flowchart
Uses rows and columns. Uses graphical symbols.
Best for multiple conditions and combinations. Best for showing program flow.
Clearly shows different rules. Clearly shows sequence of operations.
Compact for complex decisions. Can become large for complex decisions.
Useful for generating test cases. Useful for understanding program execution.

9. Steps to Create a Decision Table

  1. Identify all important conditions.
  2. Identify all possible actions.
  3. List the possible values of each condition.
  4. Generate possible combinations of conditions.
  5. Create a separate rule for each combination.
  6. Determine the appropriate action for every rule.
  7. Remove impossible or unnecessary rules.
  8. Verify the completed decision table.

10. Important Points for Examination

  • A decision table represents decision logic in tabular form.
  • Conditions describe situations that must be evaluated.
  • Actions describe what should happen.
  • Each rule represents a combination of conditions.
  • Decision tables are useful when multiple conditions exist.
  • They can help identify missing or contradictory rules.
  • They are useful for designing and testing programs.
  • Decision tables can be converted into Python if-elif-else logic.

11. Quick Summary

Decision Table = A tabular representation of conditions, rules, and actions.

Basic Structure:
Conditions → Condition Values → Rules → Actions

Common Python Statements Used:
if → First condition
elif → Additional condition
else → Default action

Decision tables are particularly useful for complex decision-making and test-case design.
```

Flowcharting,

```html

🐍 FLOWCHART

Graphical Representation of Program Logic

1. What is a Flowchart?

A Flowchart is a graphical representation of an algorithm or process. It uses standard symbols and arrows to represent the sequence of operations and decision-making steps in a program.

A flowchart helps a programmer understand the logic of a problem before writing the actual Python program.

Basic Idea:
Problem → Algorithm → Flowchart → Program → Output

2. Purpose of a Flowchart

  • To represent program logic visually.
  • To make complex problems easier to understand.
  • To plan a program before coding.
  • To identify logical errors.
  • To explain a program to others.
  • To document the program.
  • To help in debugging and testing.

3. Standard Flowchart Symbols

START / END

Terminator

Represents the beginning or termination of a program.

PROCESS

Process

Represents a calculation or processing operation.

INPUT / OUTPUT

Input / Output

Represents data input or output.

?

Decision

Represents a condition with different possible outcomes.

Flow Line

Shows the direction of program execution.

4. Basic Flowchart Structure

START
INPUT
PROCESS
OUTPUT
END

5. Example 1 – Addition of Two Numbers

Problem

Take two numbers as input and calculate their sum.

Algorithm

  1. Start.
  2. Input two numbers A and B.
  3. Calculate SUM = A + B.
  4. Display SUM.
  5. Stop.

Flowchart

START
INPUT A, B
SUM = A + B
DISPLAY SUM
END

Python Program

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

sum = a + b

print("Sum =", sum)

Output

Enter first number: 10 Enter second number: 20 Sum = 30

6. Example 2 – Even or Odd

Problem

Determine whether a given number is even or odd.

Flowchart

START
INPUT N
N % 2 == 0?
YES
PRINT EVEN
NO
PRINT ODD
END

Python Program

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

if n % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")

Output

Enter a number: 15 Odd Number

7. Example 3 – Loop Flowchart

Flowcharts can represent repetition or looping operations.

Problem

Display numbers from 1 to 5.

Flowchart

START
i = 1
i ≤ 5?
YES ↓
PRINT i
i = i + 1
Repeat until condition becomes FALSE
END

Python Program

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

Output

1 2 3 4 5

8. Advantages of Flowchart

✅ Advantages

  • Easy to understand.
  • Provides a visual representation of logic.
  • Helps in program planning.
  • Makes complex logic easier to understand.
  • Helps identify logical errors.
  • Useful for debugging.
  • Improves communication among programmers.
  • Useful for teaching programming.
  • Provides program documentation.
  • Language independent.

❌ Disadvantages

  • Creating large flowcharts can be time-consuming.
  • Complex programs may require very large diagrams.
  • Modification can be difficult.
  • Large flowcharts require more space.
  • Flow lines may cross in complex diagrams.
  • Not every programming detail is easy to represent.
  • Maintenance of large flowcharts can be difficult.
  • A major program change may require redrawing.

9. Rules for Drawing a Flowchart

  1. Use standard flowchart symbols.
  2. Begin with a START symbol.
  3. End with an END symbol.
  4. Use arrows to indicate the direction of flow.
  5. Normally draw the flow from top to bottom or left to right.
  6. Use the diamond symbol for decisions.
  7. Clearly label decision branches such as YES and NO.
  8. Avoid unnecessary crossing of flow lines.
  9. Keep the flowchart simple and readable.
  10. Use meaningful descriptions inside each symbol.

10. Algorithm vs Flowchart

Algorithm Flowchart
Written step-by-step procedure. Graphical representation of the procedure.
Uses words and statements. Uses symbols and arrows.
Usually easier to write. Usually easier to visualize.
Good for describing detailed steps. Good for showing program flow.
Can be modified relatively easily. Modification may require redrawing.

11. Important Points for Examination

  • Flowchart is a graphical representation of an algorithm.
  • Oval represents Start or End.
  • Rectangle represents Process.
  • Parallelogram represents Input or Output.
  • Diamond represents Decision.
  • Arrows indicate the direction of flow.
  • Flowcharts are useful for program planning.
  • Flowcharts help in understanding and debugging program logic.
  • Flowcharts can represent sequence, selection and repetition.

12. Quick Summary

Flowchart = Graphical representation of an algorithm or program logic.

Important Symbols:
🟢 Oval → Start / End
▭ Rectangle → Process
▱ Parallelogram → Input / Output
◇ Diamond → Decision
→ Arrow → Direction of Flow

Program Development:
Problem → Algorithm → Flowchart → Python Program → Output
```

Exit function,

```html

🐍 Exit Function in Python

Understanding Program Termination

1. What is an Exit Function?

The exit() function is used to terminate the execution of a Python program.

When Python encounters exit(), the program stops executing the remaining statements in that execution environment.

2. Syntax

exit()

A message can also be supplied:

exit("Program terminated")

3. Simple Example

print("Statement 1")

exit()

print("Statement 2")

Output

Statement 1

"Statement 2" is not executed because the program terminates when exit() is reached.

4. How exit() Works

Start Program
Execute Statements
exit()
Program Stops

5. Exit Using a Condition

An exit function is often used when a particular condition is satisfied.

age = 15

if age < 18:
    print("You are not eligible.")
    exit()

print("You are eligible.")

Output

You are not eligible.

Since the age is less than 18, the program terminates before reaching the final print().

6. Exit with a Message

marks = 25

if marks < 30:
    exit("Student has failed.")

print("Student has passed.")

Output

Student has failed.

7. sys.exit()

For Python programs, sys.exit() is generally preferred when you explicitly want to terminate program execution.
import sys

print("Program started")

sys.exit()

print("Program ended")

Output

Program started

8. exit(), quit() and sys.exit()

Function Purpose Typical Use
exit() Terminates program execution. Interactive Python use / simple examples.
quit() Terminates the Python interpreter. Interactive Python sessions.
sys.exit() Raises SystemExit to terminate execution. Python programs and scripts.

9. Important Difference

Note:

exit() and quit() are mainly intended as convenience helpers for interactive use.

In a Python script, it is better practice to use:
import sys
sys.exit()

10. exit() vs return

exit() return
Terminates the program/interpreter execution. Leaves the current function.
Can stop the whole program. Does not normally terminate the whole program.
Used for program termination. Used to send a value back from a function.

11. Example: return vs exit()

def check_number(n):

    if n < 0:
        return "Negative number"

    return "Positive number"

print(check_number(-5))
print("Program continues...")

Output

Negative number Program continues...

Here, return only exits the function. The rest of the program continues.

12. Applications of Exit

🛑 Invalid Input

Stop execution when invalid input is detected.

🔐 Authentication

Stop execution when authentication fails.

⚠ Error Handling

Terminate execution when a critical condition occurs.

🚪 Menu Programs

Exit a menu-driven program when the user chooses Exit.

13. Interactive Demonstration

Select an example to understand program termination.

Select an example.

14. Important Points for Examination

  • exit() is used to terminate program execution.
  • quit() is another interactive convenience for leaving Python.
  • sys.exit() is commonly used in Python scripts for explicit program termination.
  • return exits a function, not normally the entire program.
  • Statements after an exit operation are not executed.

15. Quick Summary

exit()

exit("message")

import sys
sys.exit()
Remember:

exit() → Stop program execution
return → Leave the current function
sys.exit() → Explicit program termination
```

default arguments.

```html

🐍 Default Arguments in Python

Understanding Default Values in Function Parameters

1. What is a Default Argument?

A default argument is a value assigned to a function parameter when the function is defined.

If the caller does not provide a value for that parameter, Python automatically uses the default value.

2. Syntax

def function_name(parameter=default_value):
    statements

The parameter is assigned a value using the = operator.

3. Simple Example

def greet(name="Student"):
    print("Hello", name)

greet()
greet("Bijan")

Output

Hello Student Hello Bijan

In the first function call, no argument is supplied. Therefore, Python uses "Student".

In the second call, "Bijan" is supplied, so the default value is replaced.

4. How Default Arguments Work

Function Definition
Default Value
Function Call
Argument Given?
Use Given / Default Value

5. Multiple Default Arguments

def student(name, course="BCA", year=1):
    print("Name:", name)
    print("Course:", course)
    print("Year:", year)

student("Rahul")

Output

Name: Rahul Course: BCA Year: 1

Here, course and year have default values.

6. Overriding a Default Argument

def student(name, course="BCA", year=1):
    print(name, course, year)

student("Rahul")
student("Anita", "BSc", 2)

Output

Rahul BCA 1 Anita BSc 2

When values are provided during the function call, they replace the default values.

7. Default Argument with Return

def power(number, exponent=2):
    return number ** exponent

print(power(5))
print(power(5, 3))

Output

25 125

The default exponent is 2. Therefore, power(5) calculates 5².

When 3 is supplied, the calculation becomes 5³.

8. Important Rule

Important: Parameters with default values should generally be placed after parameters without default values.

Correct:
def student(name, age=18):
    print(name, age)
Incorrect:
def student(age=18, name):
    print(name, age)
The second form produces a SyntaxError.

9. Parameter vs Default Argument

Concept Example Meaning
Parameter name Variable that receives a value.
Default Parameter name="Student" Parameter with a predefined value.
Argument "Bijan" Actual value passed during the function call.

10. Advantages of Default Arguments

♻ Reusability

The same function can work with or without optional values.

⚡ Simplicity

The caller does not need to provide every argument.

🧩 Flexibility

Default values can be replaced whenever necessary.

📖 Readability

Functions become easier to use and understand.

11. Interactive Demonstration

Click the buttons to understand how default arguments work.

Select an example.

12. Important Points for Examination

  • A default argument has a predefined value.
  • Default values are specified while defining the function.
  • If an argument is omitted, the default value is used.
  • A supplied argument overrides the default value.
  • Non-default parameters should come before default parameters.
  • Default arguments are useful for optional parameters.

13. Quick Summary

def function_name(parameter=default_value):
    statements

function_name()
function_name(value)
Remember:

No argument → Default value is used
Argument supplied → Supplied value is used
```

Defining Functions,

🐍 Functions in Python

Defining, Calling, Passing Arguments and Returning Values

1. What is a Function?

A function is a reusable block of Python code designed to perform a specific task.

Instead of writing the same code repeatedly, we define the code inside a function and call the function whenever required.
♻ Reusable

Write code once and execute it multiple times.

🧩 Modular

Large programs can be divided into smaller modules.

📖 Readable

Functions make programs easier to understand.

🔧 Maintainable

Changes can be made inside one function.

2. Defining a Function

Python uses the def keyword to define a function.

def function_name():
    statements

Important Parts

Part Meaning
def Keyword used to define a function.
function_name Name of the function.
() Contains parameters, if required.
: Marks the beginning of the function body.
Indented statements Statements executed when the function is called.

3. Simple Function Example

def greet():
    print("Hello, Python!")

greet()

Output

Hello, Python!

Here, greet() is the function call. When Python reaches this statement, the function body is executed.

4. Function with Parameters

A parameter is a variable defined inside the function declaration to receive data.

def greet(name):
    print("Hello", name)

greet("Bijan")

Output

Hello Bijan
Term Example Meaning
Parameter name Variable defined by the function.
Argument "Bijan" Actual value passed to the function.

5. Function with Multiple Parameters

def add(a, b):
    print("Sum =", a + b)

add(10, 20)

Output

Sum = 30

6. Function with Return Value

The return statement sends a value back from the function to the calling statement.
def square(n):
    return n * n

result = square(5)

print("Square =", result)

Output

Square = 25

7. How a Function Works

Define Function
Pass Arguments
Execute Function
Return Result
Use Result

8. Common Types of Functions

Type 1

Function without parameters and without return value.

Type 2

Function with parameters but without return value.

Type 3

Function without parameters but with return value.

Type 4

Function with parameters and return value.

9. Interactive Function Demonstration

Click a button to see how different function calls work.

Select an example above.

10. Important Points for Examination

  • Functions are defined using the def keyword.
  • A function is executed when it is called.
  • Parameters receive values passed to a function.
  • The return statement sends a value back.
  • Python functions improve code reusability.
  • Indentation is compulsory inside a function.
  • A function may have zero, one, or multiple parameters.

11. Quick Summary

def function_name(parameters):
    statements
    return value

function_name(arguments)
Remember: Define → Call → Execute → Return
```

Difference between break, continue and pass

Break, Continue and Pass in Python

Complete Tutorial with Syntax, Examples & Output

1. Introduction

In Python, break, continue and pass are special statements used to control the flow of a program.

These statements are especially important when working with for and while loops.

break

Stops the loop completely.

continue

Skips the current iteration.

pass

Does nothing.

break = STOP   |   continue = SKIP   |   pass = DO NOTHING

2. break Statement

The break statement is used to terminate a loop immediately.

Definition: The break statement terminates the nearest enclosing for or while loop.

Syntax

break

Example

for i in range(1, 11):

    if i == 6:
        break

    print(i)
Output:
1
2
3
4
5

When i becomes 6, the break statement is executed and the loop terminates.

3. How break Works

Loop Starts ↓ Condition Checked ↓ break encountered ↓ Loop Terminates ↓ Execution continues after loop

4. Practical Example of break

Suppose we want to search for a particular number in a list. Once the number is found, we can stop searching.

Example

numbers = [10, 20, 30, 40, 50]

for number in numbers:

    if number == 30:
        print("Number found")
        break
Output:
Number found

5. continue Statement

The continue statement skips the remaining statements of the current iteration and moves to the next iteration.

Definition: continue does not terminate the loop. It only skips the current iteration.

Syntax

continue

Example

for i in range(1, 11):

    if i == 6:
        continue

    print(i)
Output:
1
2
3
4
5
7
8
9
10

The value 6 is skipped, but the loop continues with the next iteration.

6. How continue Works

Loop Starts ↓ Condition Checked ↓ continue encountered ↓ Remaining statements skipped ↓ Next iteration ↓ Loop continues

7. Practical Example of continue

The following program uses continue to skip even numbers.

Example

for number in range(1, 11):

    if number % 2 == 0:
        continue

    print(number)
Output:
1
3
5
7
9

8. pass Statement

The pass statement is a null statement. It does not perform any operation.

Definition: pass is used as a placeholder when a programmer needs a statement syntactically but does not want to execute any action.

Syntax

pass

Example

for i in range(1, 6):

    if i == 3:
        pass

    print(i)
Output:
1
2
3
4
5

When i = 3, pass does nothing. Therefore, 3 is still printed.

9. Practical Example of pass

The pass statement is useful when a programmer wants to create a function but will implement it later.

Example

def calculate_result():
    pass

print("Program completed")
Output:
Program completed

10. Difference Between break, continue and pass

Statement Purpose Effect Loop Continues?
break Stop the loop Terminates the loop No
continue Skip iteration Moves to next iteration Yes
pass Do nothing No operation Yes

11. Comparing All Three Statements

Using break

for i in range(1, 6):

    if i == 3:
        break

    print(i)
Output:
1
2

Using continue

for i in range(1, 6):

    if i == 3:
        continue

    print(i)
Output:
1
2
4
5

Using pass

for i in range(1, 6):

    if i == 3:
        pass

    print(i)
Output:
1
2
3
4
5

12. break with while Loop

Example

i = 1

while i <= 10:

    if i == 5:
        break

    print(i)

    i += 1
Output:
1
2
3
4

13. continue with while Loop

Example

i = 0

while i < 5:

    i += 1

    if i == 3:
        continue

    print(i)
Output:
1
2
4
5
Important: When using continue in a while loop, make sure the loop-control variable is updated properly. Otherwise, an infinite loop can occur.

14. Real-Life Examples

Python Statement Real-Life Example
break You are searching for a book. Once you find it, you stop searching.
continue You are checking students. If one student is absent, you skip that student and check the next student.
pass A task has not been implemented yet, so you temporarily leave the block empty.

15. Important Examination Points

  • break terminates the nearest enclosing loop.
  • continue skips the current iteration.
  • pass performs no operation.
  • break does not move to the next iteration.
  • continue moves to the next iteration.
  • pass is commonly used as a placeholder.

16. Complete Comparison Table

Feature break continue pass
Terminates loop Yes No No
Skips current iteration No Yes No
Does nothing No No Yes
Next iteration No Yes Yes
Used in loops Yes Yes Yes
Used as placeholder No No Yes

17. Quick Memory Trick

BREAK → STOP THE LOOP

CONTINUE → SKIP THE CURRENT ITERATION

PASS → DO NOTHING

18. Summary

The break, continue, and pass statements are important Python control statements.

  • break: Completely terminates the loop.
  • continue: Skips the current iteration and proceeds to the next iteration.
  • pass: Performs no operation and is generally used as a placeholder.
break = STOP   |   continue = SKIP   |   pass = DO NOTHING