Python Computational Thinking Guide
Python Computational Thinking Guide
2marks Question
Decomposition
Pattern Recognition
Abstraction
Algorithm Design
7//2 = 3
7%2 = 1
= : Assignment operator → x = 5
% : Modulus → 7%2 = 1
statement
if condition:
statement
else:
statement
match variable:
case value1:
statement
case value2:
statement
if x > 5:
statement
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}
int
float
complex
Programming
Data analysis
Artificial Intelligence
Decomposition
Pattern Recognition
Abstraction
Algorithm Design
Simple to implement
Easy to parallelize
30. Python program using while loop to print numbers from 1 to 10.
i=1
while i<=10:
print(i)
i+=1
for i in range(1,6):
print(i)
32. List out any four algorithm design and problem-solving strategies.
Brute Force
Greedy Method
Dynamic Programming
Guarantees correctness
10marks questions
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.
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.
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.
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
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).
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
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.
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.
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.
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.
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.
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.
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.”
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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
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).
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.
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
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.
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.
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
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
# 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
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
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:
Sample Input/Output:
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
discount = 0
else:
discount = 0.20 * bill # 20% discount
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
else:
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
else:
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
if late_days <= 7:
fine = late_days * 5
fine = late_days * 10
else: