0% found this document useful (0 votes)
11 views37 pages

Python Computational Thinking Guide

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)
11 views37 pages

Python Computational Thinking Guide

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 Question bank

2marks Question

1. Define Computational Thinking


Computational Thinking is a problem-solving method that involves breaking down
problems, recognizing patterns, abstracting details, and designing step-by-step algorithms
to reach solutions.

2. List all the pillars of Computational Thinking.

 Decomposition

 Pattern Recognition

 Abstraction

 Algorithm Design

3. Di erentiate between decomposition and abstraction.

 Decomposition: Breaking a problem into smaller, manageable parts.

 Abstraction: Hiding unnecessary details and focusing on the main idea.

4. Explain the importance of computational thinking.


It improves logical thinking, problem-solving ability, and helps in designing e icient
algorithms applicable in programming and real-world problems.

5. Describe identifier. What are the rules for valid identifier?


An identifier is a name given to variables, functions, or objects.
Rules: Must begin with a letter/underscore, can include letters, digits, underscore, and
cannot be a keyword.

6. Write the output for 7//2 and 7%2.

 7//2 = 3

 7%2 = 1

7. Di erentiate between if...else and if...elif...else in Python.

 if…else: Used for two conditions (true/false).

 if…elif…else: Used when multiple conditions are checked.

8. Di erences between = and == operators in Python with example.

 = : Assignment operator → x = 5

 == : Comparison operator → x == 5 (checks equality).

9. Di erences between // and % operators in Python with example.

 // : Floor division → 7//2 = 3

 % : Modulus → 7%2 = 1

10. Syntax of if statement in Python


if condition:

statement

11. Syntax of if - else statement in Python

if condition:

statement

else:

statement

12. Explain syntax of match

match variable:

case value1:

statement

case value2:

statement

13. Explain the use of indentation in Python with example.


Indentation defines code blocks in Python.

if x > 5:

print("Greater") # indented block

14. Syntax of for loop in Python

for variable in sequence:

statement

15. Syntax of while loop in Python

while condition:

statement

16. List out the Data types used in Python with an example for each.

 int → x=10

 float → y=3.14

 str → "Hello"

 bool → True/False

 list → [1,2,3]

 tuple → (1,2,3)

 dict → {"a":1}
 set → {1,2,3}

17. Explain di erent data types used in Python.


Python has numeric (int, float, complex), sequence (list, tuple, string), mapping (dict), set
types, and boolean.

18. List out numeric data types in Python.

 int

 float

 complex

19. Mention the applications of Computational Thinking.

 Programming

 Problem solving in real life

 Data analysis

 Artificial Intelligence

20. Mention the major pillars of Computational Thinking.

 Decomposition

 Pattern Recognition

 Abstraction

 Algorithm Design

21. Explain the range() function with an example.


range(start, stop, step) generates a sequence of numbers.
Example: range(1,6) → [1,2,3,4,5]

22. Di erence between / and // operator.

 / → True division (decimal result).

 // → Floor division (integer result).

23. List the rules to define an identifier and give example.


Rules: Start with letter/underscore, no special characters, not a keyword.
Example: student_name

24. Explain algorithm with example.


An algorithm is a step-by-step procedure to solve a problem.
Example: Algorithm to add two numbers → Step1: Input numbers, Step2: Add, Step3:
Display result.

25. Illustrate importance of algorithms with example.


Algorithms improve e iciency and reduce errors.
Example: Sorting algorithm helps in quick data search.
26. Define flowchart. Outline any 4 di erent flowchart symbols.
Flowchart: A diagram representing steps of an algorithm.
Symbols: Oval (Start/End), Rectangle (Process), Diamond (Decision), Arrow (Flow).

27. Advantages of Brute Force strategy.

 Simple to implement

 Guarantees a solution if one exists

28. Advantages of Divide and Conquer strategy.

 E icient for large problems

 Easy to parallelize

 Reduces time complexity

29. Di erence between for loop and while loop in Python.

 for loop → Used when number of iterations is known.

 while loop → Used when condition controls repetition.

30. Python program using while loop to print numbers from 1 to 10.

i=1

while i<=10:

print(i)

i+=1

31. Python program to print numbers from 1 to 5 using for loop.

for i in range(1,6):

print(i)

32. List out any four algorithm design and problem-solving strategies.

 Brute Force

 Divide and Conquer

 Greedy Method

 Dynamic Programming

33. Identify the advantages of Brute force strategy.

 Easy to understand and implement

 Guarantees correctness

34. Explain break and continue statements.

 break → Exits the loop completely.

 continue → Skips current iteration and goes to next.


35. List any three real-world applications of Python and explain briefly.

 Web Development → Frameworks like Django, Flask.

 Data Science → Libraries like Pandas, NumPy.

 Automation → Scripts for repetitive tasks.

10marks questions

1. Discuss the importance of Computational thinking


Soln: Computational Thinking (CT) is a fundamental skill that enables individuals to
solve complex problems e ectively using logical reasoning and step-by-step
approaches. It is not limited to computer science but is applied across various
disciplines.
Importance of Computational Thinking:
1. Systematic Problem Solving:
o CT allows breaking down complex problems into smaller, manageable parts.
o Example: Breaking down an e-commerce system into modules like login, cart,
payment, and delivery.
2. Pattern Recognition:
o Helps identify similarities in problems, so the same solutions can be reused.
o Example: Recognizing that searching for an item in a library and searching data
in a database follow similar logic.
3. Abstraction and Simplification:
o Focuses only on relevant details and ignores unnecessary complexity.
o Example: When designing a tra ic system, only vehicle types and signals are
considered, not individual driver behavior.
4. Algorithmic Thinking:
o Develops the ability to design step-by-step instructions (algorithms) for solving
problems.
o Example: Algorithm for ATM withdrawal: insert card → enter PIN → choose
transaction → withdraw cash.
5. E iciency and Optimization:
o Encourages finding faster and cost-e ective solutions.
o Example: Using sorting algorithms (Quick Sort, Merge Sort) to organize large
datasets e iciently.
6. Real-World Applications:
o CT is used in robotics, artificial intelligence, machine learning, data science, and
daily life problem-solving.
o Example: GPS navigation uses CT principles to find the shortest path.
7. Interdisciplinary Use:
o Useful not only in computing but also in biology, business, mathematics,
engineering, and social sciences.
o Example: Computational biology uses CT for DNA sequencing.
8. Encourages Innovation and Creativity:
o By combining logic with creativity, CT helps in creating new apps, software, and
technologies.

Conclusion:
Computational Thinking is important because it provides a structured way to think,
solve, and optimize problems across di erent domains. It develops critical thinking,
analytical skills, and is essential in today’s technology-driven world.
2. What are the four key pillars of computational thinking? Explain Decomposition with
an example
Soln: Computational Thinking (CT) is a problem-solving process that helps in designing
e icient and logical solutions. It is built upon four key pillars, each contributing to
e ective problem-solving.

The Four Key Pillars of Computational Thinking:


1. Decomposition
o Breaking a complex problem into smaller, manageable parts.
o Makes the problem easier to solve step by step.
2. Pattern Recognition
o Observing patterns and similarities in problems.
o Helps reuse solutions for similar tasks and reduces e ort.
3. Abstraction
o Focusing on the important details and ignoring unnecessary information.
o Simplifies complex systems by highlighting what really matters.
4. Algorithm Design
o Developing step-by-step instructions to solve a problem.
o Ensures clarity, accuracy, and e iciency in solutions.

Detailed Explanation of Decomposition:


 Definition:
Decomposition is the process of breaking down a large, complex problem into smaller
sub-problems that are easier to solve.
 Why Important?
o It reduces complexity.
o Each smaller task can be handled individually.
o Tasks can be solved in parallel, making work faster.
o Solutions to smaller problems can be reused in other contexts.

Example of Decomposition:
Problem: Design an Online Shopping System.
Decomposition Approach:
1. User Login and Registration Module
2. Product Catalog Browsing Module
3. Shopping Cart Module
4. Payment Gateway Module
5. Order Tracking Module
Each module is developed separately and then combined to form the complete system.

Conclusion:
The four pillars of Computational Thinking—Decomposition, Pattern Recognition,
Abstraction, and Algorithm Design—work together to solve problems e iciently.
Among them, Decomposition is the first step, as it simplifies complex problems into
manageable parts and lays the foundation for e ective solutions.
3. Define pattern recognition and explain with suitable examples.
Soln: Definition:
Pattern Recognition is one of the key pillars of Computational Thinking. It is the
process of observing similarities, trends, or repeated structures in problems and
using them to design more e icient solutions.

Importance of Pattern Recognition:


1. Helps identify reusable solutions for similar problems.
2. Reduces time and e ort by avoiding solving the same type of problem repeatedly.
3. Makes problem-solving faster and more e icient.
4. Aids in predicting outcomes based on recurring patterns.

Steps in Pattern Recognition:


1. Identify the problem.
2. Break down into smaller instances.
3. Observe similarities or repeated behavior.
4. Generalize a common solution.

Examples of Pattern Recognition:


1. Mathematics Example:
o Problem: Finding the sum of even numbers.
o Observation: Even numbers always follow the pattern 2, 4, 6, 8, ….
o Solution: Use the formula for sum of arithmetic series.
2. Programming Example:
o Suppose we need to print the multiplication tables of 2, 3, 4, and 5.
o Pattern: All tables follow the structure number × i (where i ranges from 1 to 10).
o Instead of writing separate code for each table, we can write one general loop.
3. for num in range(2, 6):
4. for i in range(1, 11):
5. print(num, "x", i, "=", num*i)
6. Real-Life Example:
o Weather forecasting uses past data patterns to predict future weather.
o Example: If it rained at a particular season in the last 10 years, it is likely to
repeat.

Conclusion:
Pattern Recognition is essential in Computational Thinking because it helps us identify
similarities across problems, reuse solutions, and solve problems more e iciently.
It is widely applied in mathematics, computer programming, data science, and real-life
problem solving.
4. Define abstraction and explain its types using suitable examples.
Soln: Definition:
Abstraction is one of the four key pillars of Computational Thinking. It is the process
of hiding unnecessary details and focusing only on the essential features of a
problem or system. Abstraction simplifies complex problems by removing irrelevant
information and highlighting what is important.

Importance of Abstraction:
1. Reduces complexity of systems.
2. Makes problem-solving easier and clearer.
3. Helps in reusing solutions for multiple problems.
4. Improves e iciency in programming and real-life problem solving.

Types of Abstraction in Computational Thinking / Programming:


1. Data Abstraction
o Hiding the internal details of data and showing only the necessary part.
o Example: In Python, when we use a list, we don’t need to know how it is stored in
memory. We only access elements like mylist[0].
2. Control Abstraction
o Hiding the details of control structures and focusing only on the result.
o Example: Using a loop (for, while) instead of manually repeating the same code
multiple times.
3. Problem Abstraction (Generalization)
o Removing specific details and focusing on the general pattern of the problem.
o Example: To design a program for calculating area, instead of writing separate
programs for square, rectangle, and circle, we generalize the problem into a
formula-based solution depending on shape type.

Examples of Abstraction:
1. Real-Life Example:
o When driving a car, the driver only uses steering, brakes, and accelerator. The
complex details of the engine, gears, and fuel injection are hidden.
2. Programming Example:
o Consider Python function:
o print("Hello World")
The programmer only calls the function print(). The internal details of how text is
displayed on screen are hidden.
3. Mathematics Example:
o While solving algebra, instead of worrying about the actual values, we use
symbols like x and y to generalize problems.

Conclusion:
Abstraction is a powerful concept in Computational Thinking that simplifies complex
systems by hiding unnecessary details. Its types—data abstraction, control
abstraction, and problem abstraction—are widely used in computer science,
mathematics, and real-life applications to make problem-solving more e ective
5. Describe an algorithm. What are the characteristics of a good algorithm
Soln: Definition:
An algorithm is a finite step-by-step procedure or set of instructions used to solve a
specific problem or perform a particular task. It is the foundation of computational
problem solving and programming.
Example: Algorithm to add two numbers:
1. Start
2. Input two numbers a and b
3. Add a + b
4. Display the result
5. Stop

Characteristics of a Good Algorithm:


A good algorithm should satisfy the following features:
1. Finiteness:
o The algorithm must always terminate after a finite number of steps.
o Example: A loop that never ends is not a valid algorithm.
2. Definiteness (Clarity):
o Each step of the algorithm should be clear, unambiguous, and well-defined.
o Example: Instead of saying "sort numbers," specify "arrange numbers in
ascending order."
3. Input:
o An algorithm should accept zero or more inputs.
o Example: A factorial algorithm takes one number as input.
4. Output:
o An algorithm must produce at least one output (result).
o Example: A search algorithm returns the position of an element.
5. E ectiveness:
o Each step should be basic enough to be carried out easily and must contribute
towards the solution.
o Example: Using simple arithmetic operations instead of vague instructions.
6. Generality:
o The algorithm should be applicable to a broad set of problems, not just a single
instance.
o Example: A sorting algorithm should work for any list of numbers, not just one
specific list.
7. E iciency (Optimality):
o The algorithm should use minimal time and resources (memory/CPU).
o Example: Quick Sort is more e icient than Bubble Sort for large datasets.

Conclusion:
An algorithm is a step-by-step problem-solving procedure that is the backbone of
programming and computational thinking. A good algorithm must be finite, clear,
e ective, general, and e icient to ensure correctness and usability in solving real-
world problems.
6. Identify and describe the pillars of computational thinking with real time examples.
Soln: Computational Thinking (CT) is a problem-solving approach used in computer
science and other fields to design efficient solutions. It is built on four key pillars, each
playing an important role in simplifying and solving problems.

1. Decomposition
 Definition: Breaking down a complex problem into smaller, manageable parts.
 Real-time Example: In developing an online shopping system, the problem is
divided into modules such as login, product catalog, cart, payment, and delivery. Each
module can be solved independently.

2. Pattern Recognition
 Definition: Identifying similarities, trends, or repeated structures in problems.
 Real-time Example: In weather forecasting, meteorologists study patterns in
temperature, rainfall, and wind over years to predict future weather. Similarly, in
programming, printing multiplication tables uses the same repeated pattern.

3. Abstraction
 Definition: Hiding unnecessary details and focusing only on the essential features of
a problem.
 Real-time Example: When using an ATM machine, the user only sees options like
withdraw, deposit, and check balance, while the internal bank software and hardware
details remain hidden.

4. Algorithm Design
 Definition: Creating step-by-step instructions to solve a problem.
 Real-time Example: In Google Maps navigation, the shortest route is calculated
using an algorithm: start location → possible routes → compare distances → select
the shortest path.

Conclusion:
The four pillars of Computational Thinking—Decomposition, Pattern Recognition,
Abstraction, and Algorithm Design—together form the foundation of problem
solving in computer science and real life. They help us design clear, efficient, and
reusable solutions to complex problems.
7. Define token. Explain any four types of the tokens used in python with example.
Soln: Definition:
In Python, a token is the smallest unit of a program that the Python interpreter can
recognize and process. Tokens are the building blocks of a Python program.
Example: In the statement
x = 10 + 5
The tokens are: x (identifier), = (operator), 10 (literal), + (operator), 5 (literal).

Types of Tokens in Python:


Python supports several types of tokens. The major ones are:

1. Keywords
 Definition: Reserved words that have a predefined meaning in Python and cannot be
used as identifiers.
 Example:
if x > 0:
print("Positive")
Here, if is a keyword.

2. Identifiers
 Definition: Names given to variables, functions, classes, or objects in Python.
 Rules: Must start with a letter/underscore, cannot use special symbols, and cannot be
a keyword.
 Example:
name = "Alice"
age = 20
Here, name and age are identifiers.

3. Literals (Constants)
 Definition: Fixed values used in a program that cannot be changed during execution.
 Types: Numeric, String, Boolean, etc.
 Example:
x = 100 # numeric literal
y = "Hello" # string literal
z = True # boolean literal

4. Operators
 Definition: Symbols used to perform operations on variables and values.
 Example:
a = 10
b=5
print(a + b) # + is an arithmetic operator
print(a > b) # > is a relational operator

Other Tokens (for reference):


 Punctuators / Delimiters: Symbols like (), {}, [], :, , used for structure.
 Comments: Statements beginning with # are ignored by the interpreter.

Conclusion:
Tokens are the basic elements of Python programs. The main types include
keywords, identifiers, literals, and operators, each playing a vital role in writing
correct and meaningful Python code.
[Link] the importance of Computational thinking with suitable example.
Soln: Definition:
Computational Thinking (CT) is a problem-solving process that involves breaking down complex
problems, recognizing patterns, abstracting irrelevant details, and designing step-by-step
algorithms to reach effective solutions. It is a fundamental skill in programming, computer
science, and real-life problem solving.

Importance of Computational Thinking:


1. Enhances Problem-Solving Skills
o Helps in analyzing problems systematically and developing logical solutions.
o Example: Breaking a large software project into smaller modules makes development
easier.
2. Improves Efficiency
o Encourages designing optimized and systematic solutions, saving time and resources.
o Example: Using a sorting algorithm like Quick Sort instead of manually arranging data.
3. Promotes Reusability
o Recognizing patterns and creating general solutions allows reuse in similar problems.
o Example: A login module created for one application can be reused in another.
4. Supports Real-World Applications
o CT is not limited to programming; it is used in data analysis, robotics, AI, and daily life.
o Example: GPS navigation uses algorithms to find the shortest route based on traffic
patterns.
5. Encourages Innovation and Creativity
o By combining logical thinking with creativity, new solutions and technologies can be
developed.
o Example: Designing a smart irrigation system that waters plants based on soil moisture
sensors.
6. Foundation for Programming
o CT teaches how to think like a programmer, designing algorithms before coding.
o Example: Developing an online food ordering system using decomposition, abstraction,
and algorithms.

Conclusion:
Computational Thinking is essential for solving complex problems effectively and efficiently. By
applying its principles—decomposition, pattern recognition, abstraction, and algorithm design—
we can develop solutions in programming and real-life scenarios.

9. Explain if with syntax and suitable example


Soln: Definition:
The if statement in Python is a decision-making statement that allows the program
to execute a block of code only if a specified condition is True. It helps in
controlling the flow of a program based on certain conditions.

Syntax of if statement:
if condition:
statement(s)
 condition: A logical expression that evaluates to True or False.
 statement(s): Indented block of code that runs only if the condition is True.
 Python uses indentation (usually 4 spaces) to define the block of code.

Explanation:
 The if statement tests a condition.
 If the condition is True, the indented block is executed.
 If the condition is False, the block is skipped.

Example 1: Checking a positive number


num = 10

if num > 0:
print("The number is positive")
Output:
The number is positive
Explanation:
 The condition num > 0 is True, so the print statement inside the if block is executed.

Example 2: Condition not satisfied


num = -5

if num > 0:
print("The number is positive")
Output:
# No output
Explanation:
 The condition num > 0 is False, so the block inside if is skipped.

Conclusion:
The if statement is a fundamental decision-making tool in Python, allowing
programs to execute code conditionally. It forms the basis for more complex
conditional statements like if…else and if…elif…else
10. Explain if else construct with syntax and suitable example
Soln: Definition:
The if-else statement in Python is a decision-making construct that allows a
program to execute one block of code if a condition is True and another block if
the condition is False.
It is used when there are two possible outcomes for a condition.

Syntax of if-else statement:


if condition:
statement(s) # executed if condition is True
else:
statement(s) # executed if condition is False
 condition: A logical expression that evaluates to True or False.
 statement(s): Indented code blocks executed based on the condition.

Explanation:
 Python first evaluates the if condition.
 If the condition is True, the if block runs.
 If the condition is False, the else block runs.
 Indentation is important to define code blocks.

Example 1: Checking if a number is positive or negative


num = 10

if num >= 0:
print("The number is positive")
else:
print("The number is negative")
Output:
The number is positive
Explanation:
 Condition num >= 0 is True, so the if block executes.
 If num were -5, the else block would execute, printing “The number is negative.”

Example 2: Checking eligibility to vote


age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Output:
Not eligible to vote
Explanation:
 The condition age >= 18 is False, so the program executes the else block.

Conclusion:
The if-else construct allows Python programs to make decisions and execute
alternative actions based on conditions. It is essential for controlling the flow of
execution and forms the foundation for more complex conditional statements like if-
elif-else.
11. Explain various relational operators using if else construct with a neat algorithm and
lowchart.
Soln: Relational Operators in Python:
Relational operators are used to compare two values and return a Boolean result
(True or False).
Operator Description Example

== Equal to x == y

!= Not equal to x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Explanation Using if-else Construct:


The if-else construct can be used to check relational conditions between two
numbers.
Example: Check the relationship between two numbers a and b.
a = 10
b = 20

if a == b:
print("a is equal to b")
elif a > b:
print("a is greater than b")
else:
print("a is less than b")
Output:
a is less than b
Explanation:
 First, a == b is checked.
 Then a > b is checked if the first condition is False.
 If both are False, the else block executes.

Algorithm to Compare Two Numbers Using Relational Operators:


Step 1: Start
Step 2: Read two numbers a and b
Step 3: Check if a == b
- If True → Print “a is equal to b”
Step 4: Else, check if a > b
- If True → Print “a is greater than b”
Step 5: Else
- Print “a is less than b”
Step 6: Stop

Flowchart:
┌─────────┐
│ Start │
└─────────┘


┌────────────┐
│ Input a, b │
└────────────┘


┌───────────────┐
│ a == b ? │
└───────────────┘
/ \
Yes No
/ \
Print "a=b" ┌───────────────┐
│a>b? │
└───────────────┘
/ \
Yes No
/ \
Print "a>b" Print "a<b"


┌─────────┐
│ Stop │
└─────────┘
Conclusion:
Relational operators are used to compare values in Python. Using the if-else
construct along with relational operators, programs can make decisions and take
different actions based on comparisons. Algorithms and flowcharts help in
systematically designing such decision-making programs.
12. Explain relational operators using elif construct with a neat algorithm and flowchart.
Soln: Relational Operators in Python:
Relational operators are used to compare two values and return a Boolean value
(True or False).
Operator Description Example

== Equal to x == y

!= Not equal to x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Explanation Using elif Construct:


The elif construct allows checking multiple conditions in sequence. Only the block
corresponding to the first True condition executes.
Example: Compare two numbers a and b using relational operators:
a = 15
b = 20

if a == b:
print("a is equal to b")
elif a > b:
print("a is greater than b")
elif a < b:
print("a is less than b")
Output:
a is less than b
Explanation:
 First, if a == b is checked. False → moves to next condition.
 elif a > b is checked. False → moves to next condition.
 elif a < b is True → executes the corresponding block.

Algorithm to Compare Two Numbers Using elif:


1. Start
2. Read two numbers a and b
3. If a == b → Print “a is equal to b”
4. Else if a > b → Print “a is greater than b”
5. Else if a < b → Print “a is less than b”
6. Stop

Flowchart:
┌─────────┐
│ Start │
└─────────┘


┌────────────┐
│ Input a, b │
└────────────┘


┌───────────────┐
│ a == b ? │
└───────────────┘
/ \
Yes No
/ \
Print "a=b" ┌───────────────┐
│a>b? │
└───────────────┘
/ \
Yes No
/ \
Print "a>b" ┌───────────────┐
│a<b? │
└───────────────┘
/ \
Yes No
/ \
Print "a<b" End


┌─────────┐
│ Stop │
└─────────┘

Conclusion:
Using relational operators with elif, we can check multiple conditions efficiently
without writing nested if-else statements.
 It simplifies decision-making in Python programs.
 Algorithm and flowchart provide a structured way to design and understand the
logic.
13. Explain match statement in python with syntax and suitable example.
Soln: Definition:
The match statement in Python is a control flow structure introduced in Python
3.10. It allows the program to compare a variable against multiple patterns and
execute the corresponding block of code. It is similar to switch-case statements in
other programming languages.

Syntax of match Statement:


match variable:
case value1:
statement(s)
case value2:
statement(s)
case _:
statement(s) # default case
 variable: The expression or value to be matched.
 case value: A possible value or pattern to compare with the variable.
 case _: The default block executed if no other case matches (optional).

Explanation:
 Python evaluates the variable against each case.
 The first matching case executes its block.
 If no case matches, the _ (underscore) block executes as a default.
 Indentation is mandatory to define code blocks.

Example 1: Day of the Week


day = "Monday"

match day:
case "Monday":
print("Start of the work week")
case "Wednesday":
print("Midweek day")
case "Friday":
print("Last work day")
case _:
print("Weekend or other day")
Output:
Start of the work week
Explanation:
 The variable day matches "Monday".
 The corresponding block executes.
 If day were "Sunday", the default case _ would execute.
Example 2: Simple Calculator
operation = "add"
a = 10
b=5

match operation:
case "add":
print(a + b)
case "subtract":
print(a - b)
case _:
print("Invalid operation")
Output:
15
Explanation:
 The variable operation matches "add".
 The addition block executes, producing the result.

Advantages of match statement:


1. Simplifies multiple conditional checks.
2. More readable than nested if-elif-else for many cases.
3. Supports pattern matching beyond simple value comparison.

Conclusion:
The match statement is a modern, clean, and efficient way to handle multiple
conditions in Python. By comparing a variable against multiple patterns, it improves
code readability and maintainability, making it ideal for decision-making tasks.
14. Explain while loop with syntax.
Soln: Definition:
The while loop in Python is a control flow statement used to repeat a block of code
as long as a specified condition is True.
It is ideal when the number of iterations is not known in advance and depends on a
condition.

Syntax of while loop:


while condition:
statement(s)
 condition: A logical expression that evaluates to True or False.
 statement(s): The indented block of code that executes repeatedly while the
condition is True.

Explanation:
1. The while loop first checks the condition.
2. If the condition is True, the block of code executes.
3. After executing the block, the condition is re-evaluated.
4. If the condition becomes False, the loop terminates.
5. Proper increment/decrement or exit condition must be included to avoid infinite
loops.

Example 1: Print numbers from 1 to 5


i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
 Starts with i = 1.
 Prints i and increments by 1.
 Continues until i becomes 6, which makes the condition i <= 5 False.

Example 2: Sum of first 5 natural numbers


i=1
sum = 0
while i <= 5:
sum += i
i += 1
print("Sum =", sum)
Output:
Sum = 15
Explanation:
 Keeps adding i to sum while i <= 5.
 Increments i each iteration to eventually terminate the loop.

Conclusion:
The while loop is a fundamental iteration control structure in Python, useful when
the number of repetitions depends on a condition. Proper handling of loop conditions
prevents infinite loops and ensures correct program execution.
15. Explain for loop with syntax. Write a python program to find the factorial of a given
number.
Soln: Definition:
The for loop in Python is a control flow statement used to iterate over a sequence
(like a list, tuple, string, or range) and execute a block of code a fixed number of
times.
It is ideal when the number of iterations is known in advance.

Syntax of for loop:


for variable in sequence:
statement(s)
 variable: Takes each value from the sequence in order.
 sequence: Any iterable object like a list, string, or range.
 statement(s): Indented block of code executed in each iteration.

Explanation:
1. Python picks each element from the sequence one by one.
2. Executes the indented block for each element.
3. After the last element, the loop terminates.

Example: Python program to find factorial of a given number using for loop
# Input from the user
num = int(input("Enter a number: "))
factorial = 1

# Loop from 1 to num


for i in range(1, num + 1):
factorial *= i # multiply factorial by i in each iteration

# Display the result


print("Factorial of", num, "is", factorial)
Sample Output:
Enter a number: 5
Factorial of 5 is 120
Explanation:
 The for loop iterates from 1 to num (inclusive).
 factorial is multiplied by each i in the sequence.
 After the loop ends, the final factorial value is printed.

Conclusion:
The for loop is used for fixed iterations over sequences. It is simple, readable, and
prevents errors associated with manually controlling loop counters, unlike a while
loop.
The factorial program demonstrates using for loop for repeated multiplication to
solve a computational problem.
16. Demonstrate the usage of iterative/looping statements in python with examples.

Soln: Definition:
Iterative or looping statements in Python allow a block of code to execute
repeatedly based on a condition or sequence. They are essential when a task needs to
be performed multiple times.
Python supports two main types of loops:

1. while Loop
 Definition: Repeats a block of code as long as a condition is True.
 Syntax:
while condition:
statement(s)
 Example 1: Print numbers from 1 to 5
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
 Explanation: The loop continues until i > 5.
 Example 2: Sum of first 5 numbers
i=1
sum = 0
while i <= 5:
sum += i
i += 1
print("Sum =", sum)
Output:
Sum = 15

2. for Loop
 Definition: Iterates over a sequence or range of values for a fixed number of times.
 Syntax:
for variable in sequence:
statement(s)
 Example 1: Print numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
 Example 2: Factorial of a number
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)
Output:
Factorial of 5 is 120
3. break and continue in Loops
 break: Exits the loop immediately.
 continue: Skips the current iteration and moves to the next.
Example: Using break
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
Example: Using continue
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5

Conclusion:
Iterative statements (while and for) allow Python programs to execute repetitive
tasks efficiently.
 while loops are used when iterations depend on a condition.
 for loops are used for fixed iterations over sequences.
 break and continue provide additional control over loops.
17. Explain brute force and divide and conquer algorithm design strategies to solve a
problem.

Soln:
1. Brute Force Strategy
Definition:
The Brute Force strategy is a straightforward approach to solve a problem by trying all
possible solutions and selecting the correct one.
It is simple but may not be efficient for large problems.
Steps in Brute Force:
1. Understand the problem clearly.
2. Generate all possible solutions.
3. Check each solution for correctness.
4. Select the solution that satisfies the problem.
Example:
 Problem: Find the largest number in a list [4, 7, 1, 9, 3].
 Brute Force Approach: Compare each number with every other number to find the
largest.
numbers = [4, 7, 1, 9, 3]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print("Largest number is:", max_num)
Output:
Largest number is: 9
Advantages:
 Simple to implement.
 Easy to understand.
Disadvantages:
 Inefficient for large datasets.
 High time complexity (many computations).

2. Divide and Conquer Strategy


Definition:
The Divide and Conquer (D&C) strategy solves a problem by breaking it into smaller
subproblems, solving each subproblem independently, and combining their solutions to get
the final result.
Steps in Divide and Conquer:
1. Divide: Split the problem into smaller subproblems.
2. Conquer: Solve each subproblem recursively.
3. Combine: Merge the solutions of subproblems to form the final solution.
Example:
 Problem: Find the maximum element in a list [4, 7, 1, 9, 3] using D&C.
 Approach:
o Divide the list into two halves [4, 7] and [1, 9, 3].
o Recursively find the maximum in each half.
o Compare the two maximums to get the final result.
Python Example:
def find_max(arr):
if len(arr) == 1:
return arr[0]
mid = len(arr) // 2
left_max = find_max(arr[:mid])
right_max = find_max(arr[mid:])
return max(left_max, right_max)

numbers = [4, 7, 1, 9, 3]
print("Largest number is:", find_max(numbers))
Output:
Largest number is: 9
Advantages:
 More efficient than brute force for large problems.
 Reduces time complexity by dividing problem into smaller parts.
Disadvantages:
 Requires recursive thinking.
 Slightly complex to implement compared to brute force.

Conclusion:
 Brute Force: Simple, tries all possibilities, suitable for small problems.
 Divide and Conquer: Efficient, splits problems, solves recursively, suitable for large
datasets.
 Both strategies are fundamental in algorithm design and problem-solving.
18. Describe the brute force technique of problem solving. Explain various steps involved in
Brute force method. Also list its advantages and disadvantages
Soln: Definition:
The Brute Force technique is a straightforward and simple problem-solving approach
where all possible solutions are tried one by one until the correct solution is found.
It does not require advanced techniques but is generally less efficient for large problems.

Steps Involved in Brute Force Method:


1. Understand the Problem:
o Analyze the problem clearly to know what is required as input and output.
2. Generate All Possible Solutions:
o Consider all possible cases or solutions that could solve the problem.
3. Test Each Solution:
o Check each generated solution to see if it satisfies the problem’s requirements.
4. Select the Correct Solution:
o Once the correct solution is found, select it as the final answer.
5. Stop:
o Terminate the process after finding the solution.

Example:
 Problem: Find the largest number in the list [4, 7, 1, 9, 3].
 Brute Force Approach: Compare each element with all others to find the largest.
numbers = [4, 7, 1, 9, 3]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print("Largest number is:", max_num)
Output:
Largest number is: 9

Advantages of Brute Force Technique:


1. Simple and easy to understand.
2. Easy to implement for small problems.
3. Does not require complex logic or data structures.
4. Guarantees a correct solution if all possibilities are tested.

Disadvantages of Brute Force Technique:


1. Inefficient for large datasets because it checks all possibilities.
2. High time complexity, especially for combinatorial problems.
3. Not suitable for problems with many possible solutions.
4. Consumes more computational resources (memory and CPU) for large problems.

Conclusion:
The Brute Force method is a basic problem-solving strategy suitable for small-scale
problems. It is easy to implement but becomes inefficient for complex or large problems,
where other strategies like Divide and Conquer or Greedy algorithms are preferred.
19. Explain the key features of divide and conquer method. Mention the steps involved and
illustrate it using an example
Soln: Definition:
The Divide and Conquer (D&C) method is an algorithm design strategy that solves a
problem by:
1. Dividing it into smaller subproblems,
2. Conquering each subproblem individually,
3. Combining the solutions of subproblems to get the final result.
It is widely used in efficient algorithms like Merge Sort, Quick Sort, Binary Search, etc.
Key Features of Divide and Conquer:
1. Problem Division: The original problem is split into smaller subproblems of the
same type.
2. Recursion: Subproblems are solved recursively until they become simple enough to
solve directly.
3. Combination: Solutions of subproblems are merged to solve the original problem.
4. Efficiency: Reduces time complexity compared to brute force methods.
5. Reusability: Subproblem solutions can often be reused in multiple steps.

Steps Involved in Divide and Conquer:


1. Divide: Break the problem into smaller subproblems.
2. Conquer: Solve each subproblem recursively.
3. Combine: Merge the solutions of subproblems to get the final solution.

Example: Finding the Maximum Element in a List


Problem: Find the largest number in [4, 7, 1, 9, 3] using Divide and Conquer.
Approach:
1. Divide the list into two halves: [4, 7] and [1, 9, 3].
2. Recursively find the maximum in each half.
3. Compare the maximums of both halves to get the final maximum.
Python Code:
def find_max(arr):
if len(arr) == 1:
return arr[0]
mid = len(arr) // 2
left_max = find_max(arr[:mid])
right_max = find_max(arr[mid:])
return max(left_max, right_max)

numbers = [4, 7, 1, 9, 3]
print("Largest number is:", find_max(numbers))
Output:
Largest number is: 9

Conclusion:
The Divide and Conquer strategy is an efficient way to solve complex problems by
breaking them into smaller, manageable subproblems.
It reduces computation compared to brute force, uses recursion effectively, and is widely
applied in sorting, searching, and other algorithmic problems.

20. List the different algorithms/ approaches to solve the problems. Explain brute force method
to solve the problems. List the advantages of brute force approach.
Soln: 1. Different Algorithms/Approaches to Solve Problems:
1. Brute Force Method: Try all possible solutions and select the correct one.
2. Divide and Conquer: Break the problem into smaller subproblems, solve each, and
combine results.
3. Greedy Method: Make the best choice at each step to reach an optimal solution.
4. Dynamic Programming: Solve complex problems by breaking them into simpler
overlapping subproblems and storing solutions.
5. Backtracking: Explore all possible solutions recursively and backtrack if a solution
path fails.
6. Heuristic/Approximation Methods: Solve problems using rules of thumb or
approximations when exact solutions are hard.

2. Brute Force Method


Definition:
The Brute Force method is a straightforward problem-solving approach where all
possible solutions are tried one by one until the correct solution is found.
Steps to Solve a Problem Using Brute Force:
1. Understand the problem clearly.
2. Generate all possible solutions for the problem.
3. Test each solution to see if it satisfies the problem.
4. Select the correct solution that meets the requirements.
5. Stop once the solution is found.
Example:
 Problem: Find the largest number in the list [4, 7, 1, 9, 3].
 Brute Force Approach: Compare each number to find the largest.
numbers = [4, 7, 1, 9, 3]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print("Largest number is:", max_num)
Output:
Largest number is: 9

3. Advantages of Brute Force Approach:


1. Simple and easy to understand.
2. Easy to implement, especially for small problems.
3. Does not require advanced techniques or complex data structures.
4. Guaranteed to find the correct solution if all possibilities are checked.
5. Useful for problems with small input size or when efficiency is not a concern.

Conclusion:
The Brute Force method is a basic and reliable problem-solving strategy suitable for
small-scale problems. It is simple and guarantees a solution, though it becomes inefficient for
larger datasets.
21. Write a Python program to find reverse of a given number.
Soln: Python Program:
# Input from the user
num = int(input("Enter a number: "))
reverse = 0
temp = num

# Loop to reverse the number


while temp > 0:
digit = temp % 10 # Get the last digit
reverse = (reverse * 10) + digit # Append digit to reverse
temp = temp // 10 # Remove last digit from temp

# Display the reversed number


print("Reverse of", num, "is", reverse)

Sample Input/Output:
Enter a number: 12345
Reverse of 12345 is 54321

22. Write a Python algorithm and program to check the given number is prime or not.
Soln: Algorithm to Check Prime Number:
Input: A number n
Output: Whether n is prime or not
Steps:
1. Start
2. Read the number n
3. If n <= 1, then print “Not Prime” and stop
4. Initialize a variable is_prime = True
5. For i from 2 to sqrt(n) (or n-1 for simplicity):
o If n % i == 0:
 Set is_prime = False
 Break the loop
6. If is_prime is True, print “Prime”
7. Else, print “Not Prime”
8. Stop

Python Program:
# Input from the user
n = int(input("Enter a number: "))
# Check if n is less than or equal to 1
if n <= 1:
print(n, "is not a prime number")
else:
is_prime = True
# Check for factors from 2 to n-1
for i in range(2, n):
if n % i == 0:
is_prime = False
break
# Display result
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")

Sample Input/Output:
Enter a number: 7
7 is a prime number
Enter a number: 12
12 is not a prime number
23. Write a program to ind sum and average of 'n' numbers using any loop.
Soln: Python Program Using for Loop:
# Input number of elements
n = int(input("Enter the number of elements: "))

# Initialize sum
total = 0

# Loop to read n numbers and calculate sum


for i in range(1, n + 1):
num = float(input(f"Enter number {i}: "))
total += num

# Calculate average
average = total / n

# Display results
print("Sum of", n, "numbers is:", total)
print("Average of", n, "numbers is:", average)

Sample Input/Output:
Enter the number of elements: 4
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Sum of 4 numbers is: 100.0
Average of 4 numbers is: 25.0
24. Write a Python program to calculate the sum of first 10 natural numbers using use
while loop

Soln: Python Program:


# Initialize variables
i=1 # Counter
total = 0 # Sum

# Loop to calculate sum of first 10 natural numbers


while i <= 10:
total += i
i += 1
# Display the result
print("Sum of first 10 natural numbers is:", total)

Output:
Sum of first 10 natural numbers is: 55
25. Write an algorithm to find the square of a number. Draw a flowchart for the same
Soln: Algorithm to Find the Square of a Number

Input: A number n
Output: Square of n

Steps:

1. Start

2. Read the number n

3. Calculate the square: square = n * n

4. Display the value of square

5. Stop
┌─────────┐

│ Start │

└─────────┘

┌────────────┐

│ Input n │

└────────────┘

┌───────────────────┐

│ square = n * n │

└───────────────────┘

┌───────────────────┐

│ Print square │

└───────────────────┘


┌─────────┐

│ Stop │

└─────────┘

[Link] a python program to take a number as input from the user and print its mul plica on table.
Soln: Python Program:

# Input from the user

num = int(input("Enter a number to print its multiplication table: "))

# Loop from 1 to 10 to generate the table

for i in range(1, 11):

print(f"{num} x {i} = {num * i}")

Sample Input/Output:

Enter a number to print its multiplication table: 5

5x1=5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

27. Write a Python program that asks the user for the bill amount and prints the final amount a er
discount.A store offers discounts based on the bill amount:If bill < 500 → No discountIf 500 ≤ bill < 2000
→ 10% discountIf bill ≥ 2000 → 20% discount
Soln: # Input the bill amount from the user

bill = float(input("Enter the bill amount: "))

# Check discount based on bill amount

if bill < 500:

discount = 0

elif bill < 2000:

discount = 0.10 * bill # 10% discount

else:
discount = 0.20 * bill # 20% discount

# Calculate final amount

final_amount = bill - discount

# Display the result

print("Original Bill Amount: ₹", bill)

print("Discount: ₹", discount)

print("Final Amount to Pay: ₹", final_amount)

28. Write a Python program to check whether a person is eligible for a bank loan or [Link] program
should take salary and credit score as input.A person is eligible for a loan if: Salary is greater than or equal
to 25,000 and Credit score is greater than or equal to 700. Otherwise, the person is not eligible
Soln: # Input salary and credit score from the user

salary = float(input("Enter your salary: "))

credit_score = int(input("Enter your credit score: "))

# Check loan eligibility

if salary >= 25000 and credit_score >= 700:

print("Congratulations! You are eligible for the bank loan.")

else:

print("Sorry! You are not eligible for the bank loan.")

29. Write a Python program that performs the following tasks:• Read the customer name and meter
number.• Read the previous month’s reading (old reading) and the current month’s reading (new
reading).• Calculate the units consumed using:units = new_reading - old_reading• Calculate the monthly
bill at the rate of ₹5 per unit if units consumed is less than 100 else ₹10 per [Link] the customer
details, units consumed, and the total bill amount
Soln: # Read customer details

customer_name = input("Enter customer name: ")

meter_number = input("Enter meter number: ")

# Read previous and current month readings

old_reading = float(input("Enter previous month's reading: "))

new_reading = float(input("Enter current month's reading: "))

# Calculate units consumed

units = new_reading - old_reading

# Calculate bill based on units consumed


if units < 100:

bill = units * 5 # ₹5 per unit

else:

bill = units * 10 # ₹10 per unit

# Display customer details and bill

print("\n--- Electricity Bill ---")

print("Customer Name:", customer_name)

print("Meter Number:", meter_number)

print("Units Consumed:", units)

print("Total Bill Amount: ₹", bill)

30. Ravi borrowed a book from the library but forgot to return it on me. The librarian calculates fine
based on days late:• Within 7 days → No fine• 8–14 days → ₹5 per day• 15–30 days → ₹10 per day•
More than 30 days → Membership cancelledInput: Number of late [Link]: Fine amount or
cancella on message
Soln: # Input number of late days

late_days = int(input("Enter number of days late: "))

# Calculate fine or cancellation based on late days

if late_days <= 7:

print("No fine. Please return the book.")

elif late_days <= 14:

fine = late_days * 5

print("Fine amount: ₹", fine)

elif late_days <= 30:

fine = late_days * 10

print("Fine amount: ₹", fine)

else:

print("Membership cancelled due to excessive delay.")

You might also like