0% found this document useful (0 votes)
17 views106 pages

PBA - Computer QIB

The document outlines various programming tasks and questions related to Python, including creating user-defined functions, analyzing rainfall data, recording student attendance, and using algorithms like Binary Search and Insertion Sort. It also discusses the development of a Minimum Viable Product (MVP) for an online merchandise store, emphasizing critical features and future improvements. Additionally, it evaluates a dashboard design for an online digital library, suggesting enhancements for usability and engagement.
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)
17 views106 pages

PBA - Computer QIB

The document outlines various programming tasks and questions related to Python, including creating user-defined functions, analyzing rainfall data, recording student attendance, and using algorithms like Binary Search and Insertion Sort. It also discusses the development of a Minimum Viable Product (MVP) for an online merchandise store, emphasizing critical features and future improvements. Additionally, it evaluates a dashboard design for an online digital library, suggesting enhancements for usability and engagement.
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

PBA - QUESTION ITEM BANK DEVELOPMENT

HSSC-II
COMPUTER
Ser SLO Section Questions Answer
1. Q No 1. Aim:
a) Write a Python program that defines a user-defined
function which repeatedly accepts integer input from To write a Python program using a user-defined function that accepts
the user. integers, calculates their squares, counts valid inputs, and terminates
The function should: on a negative number.
• Calculate and display the square of each entered
number Program:
• Maintain a count of valid inputs # User-defined function
• Terminate execution only when a negative number def process_numbers():
is entered count = 0
• Display the total count of numbers processed
before termination. while True:
b) You plan to launch a small-scale online custom num = int(input("Enter an integer (negative number to stop): "))
merchandise store and decide to build a Minimum
Viable Product (MVP) to validate your business idea if num < 0:
with real users. break
i. Identify the single most critical feature that must
be included in the MVP to test customer interest square = num * num
effectively. print("Square of", num, "is:", square)
count += 1
ii. Select one suitable tool and one technology for:
print("Total valid numbers entered:", count)
o Frontend development
o Backend development # Function call
o Justify your selection briefly. process_numbers()
iii. After releasing the MVP and collecting feedback
from early users, propose any three future Output:
improvements that would enhance usability, Enter an integer (negative number to stop): 5
performance, Square of 5 is: 25
or business growth. Enter an integer (negative number to stop): 3
Square of 3 is: 9
Enter an integer (negative number to stop): -1
Total valid numbers entered: 2
Page 1 of 102
Ser SLO Section Questions Answer

Result:

The program successfully calculates the square of each entered


number and displays the total count before termination.
i. Most Critical Feature for MVP
The most critical feature is:
Product Display with Order/Buy Option
This feature allows customers to:
• View products
• Select items
• Place an order
This helps to test real customer interest in the merchandise.
ii. Suitable Tools and Technologies
Frontend Development
• Tool: Visual Studio Code
• Technology: HTML, CSS, JavaScript
Justification:
HTML and CSS are easy to use for beginners and suitable for
creating simple web pages. JavaScript makes the website
interactive. VS Code is simple and widely used.
Backend Development
• Tool: PyCharm or VS Code
• Technology: Python (Flask Framework)
Justification:
Flask is lightweight and easy for beginners. It is suitable for building a
simple MVP quickly and handling user orders.
iii. Three Future Improvements
1. Online Payment Integration
Add secure payment methods like EasyPaisa or JazzCash to
increase sales.
2. User Account System
Allow customers to create accounts and track orders.
3. Performance Optimization
Improve website speed and mobile responsiveness for better
user experience.
Page 2 of 102
Ser SLO Section Questions Answer
Q. 2 You are a climate data analyst studying monthly Here is the answer according to Class 11 Practical Format (Simple
rainfall (in mm) to identify weather patterns using Python & Exam-Oriented):
lists. Analyze the given data carefully.
Q No 2
Use the following rainfall data (in mm): Aim:
[50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65] To analyze monthly rainfall data using Python lists and perform basic
a) Store the given rainfall data in a Python list and statistical operations.
display it along with the total number of months
recorded. Consider the following Python (a)
statements: Program to Store and Display Rainfall Data
rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65] rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]
print(max(rainfall))
print(min(rainfall)) print("Rainfall Data:", rainfall)
i. Write the exact output produced by the code. print("Total number of months recorded:", len(rainfall))
ii. Explain what these two values represent in the context Output:
of rainfall analysis. Rainfall Data: [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]
b) The following Python program is intended to calculate Total number of months recorded: 12
the average monthly rainfall, but it contains errors.
Given Code:
rainfall = [50, 80, 60, 30, rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]
120, 90, 70, 100, 85, 95, 40, 65] print(max(rainfall))
avg = sum(rainfall) / 12; print(min(rainfall))
print("average rainfall = ", average) i. Exact Output:
i. Identify all errors in the code. 120
ii. Rewrite the corrected version of the program. 30
• Modify the given Python code so that it: ii. Explanation:
• 120 mm represents the highest rainfall recorded in a month.
• Prints the names of months that have dry rainfall • 30 mm represents the lowest rainfall recorded in a month.
(rainfall less than 70 mm) These values help identify the wettest and driest months.
• Displays the total number of dry months Given Incorrect Program:
rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65] rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]
count = 0 avg = sum(rainfall) / 12;
for i in range(10): print("average rainfall = ", average)
if rainfall[i] >= 70: i. Errors in the Code:
count = count + 1 1. Variable name mismatch: avg is defined but average is
printed.
Page 3 of 102
Ser SLO Section Questions Answer
print("total months with greater than 70mm rainfall:", 2. Hardcoding 12 is not recommended (should use len(rainfall)).
count) 3. Semicolon (;) is unnecessary in Python (optional but not
needed).
ii. Corrected Program:
rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]

average = sum(rainfall) / len(rainfall)

print("Average rainfall =", average)


Output:
Average rainfall = 73.75
Corrected & Modified Program:
rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]

months = ["January", "February", "March", "April", "May", "June",


"July", "August", "September", "October", "November",
"December"]

count = 0

for i in range(len(rainfall)):
if rainfall[i] < 70:
print(months[i], "has dry rainfall:", rainfall[i], "mm")
count = count + 1

print("Total dry months:", count)

Output:
January has dry rainfall: 50 mm
March has dry rainfall: 60 mm
April has dry rainfall: 30 mm
November has dry rainfall: 40 mm
December has dry rainfall: 65 mm
Total dry months: 5

Page 4 of 102
Ser SLO Section Questions Answer
Q. 3 Here is the answer according to Class 11 Practical Copy Format
(Simple & Exam-Oriented):
A college instructor wants to digitally record and analyze
student attendance for a class using Python. Q No 3
i) Write a Python program that takes user input for a Aim:
student’s attendance status.
a. The program should: Accept input as "P" for To write a Python program that records and analyzes student
present or "A" for absent attendance using user input and loops.
b. Display an appropriate message based on the
input i) Program for Single Student Attendance
ii) Enhance the program to record attendance for Program:
exactly five (05) students using a loop. ii.
Ensure that the program asks for attendance one present_count = 0
student at a time.
for i in range(5):
iii) After all attendance entries are recorded, status = input("Enter attendance for student " + str(i+1) + " (P/A): ")
calculate and display the total number of
students present. if status == "P":
print("Student", i+1, "is Present.")
iv) Extend the program further to calculate and print present_count += 1
the percentage of students present, formatted elif status == "A":
clearly with a percentage sign (%). print("Student", i+1, "is Absent.")
else:
print("Invalid input!")

print("Total number of students present:", present_count)


iv percentage = (present_count / 5) * 100
print("Percentage of students present:", percentage, "%")
Q. 4 a)
Write a step-by-step algorithm that takes three different Algorithm:
integers as input and displays the smallest value. Your 1. Start
algorithm should clearly show input, processing, and 2. Input three integers: A, B, and C
output steps. 3. If A < B and A < C, then
b) Display A is the smallest number
The following list contains numbers arranged in descending 4. Else if B < A and B < C, then
order: Display B is the smallest number
Page 5 of 102
Ser SLO Section Questions Answer
93, 87, 83, 71, 65, 52, 47, 36, 10 5. Else
Apply the Binary Search algorithm to locate the number Display C is the smallest number
36. 6.
Show the comparison steps performed at each stage until
the number is found.

Q. 5

The following Boolean function is given:

a. Simplify the given Boolean function using a


Karnaugh Map, clearly showing:
• Group formation
• Elimination of variables
b. Using the simplified Boolean expression obtained
above, construct the corresponding logic circuit
using appropriate logic gates.

2. Q.1 try:
# Open the file in read mode
Write a Python program that opens an existing text file in file = open("[Link]", "r")
read mode and displays its contents line by line using a
suitable loop. line_number = 1
The program should:
• Display line numbers along with each line # Read file line by line
• Handle the situation gracefully if the file does for line in file:
not exist print("Line", line_number, ":", [Link]())
line_number += 1

[Link]()

except FileNotFoundError:
print("Error: The file does not exist.")

Page 6 of 102
Ser SLO Section Questions Answer
Q. 2 i) Most Effective Design Element
The most effective design element in the dashboard is the clear
visual hierarchy and organized grid layout.
Justification:
• The title “Online Digital Library” is placed at the top, making
the purpose immediately clear.
• Information is divided into well-defined sections such as Top
Book Categories, Popular Authors, Top Fiction Books, etc.
• Charts are placed inside separate boxes, preventing clutter.
• Different colors are used to distinguish categories and data
types.
This structured layout improves user understanding and
navigation because users can quickly locate relevant information
without confusion.
ii) Suggested Design or Functional Improvements
To increase usability and engagement, the following improvements
can be made:
1. Interactive Filters
o Add filters (e.g., by month, category, or author).
o This allows users to customize the displayed data.
2. Search Bar
o Add a search feature to quickly find specific books or
authors.
3. Clickable Charts
A prototype dashboard for an online digital library is o Allow users to click on a chart section to see detailed
shown above. data.
The dashboard displays information related to book 4. Tooltips on Hover
categories, user preferences, and sales trends using charts o Show exact values when hovering over bars or pie
and visual elements. chart sections.
i) Critically analyze the interface and identify the These changes improve interaction and functionality, not just
most effective design element that improves appearance.
user understanding or navigation. Justify your iii) Evaluation of Labels, Titles, and Legends
answer with reference to layout, color usage, or The labels and titles are mostly clear, such as:
visual hierarchy. • Top Book Categories
ii) Suggest specific design or functional changes • Library Overview
that would increase user engagement and • Student Interest Areas

Page 7 of 102
Ser SLO Section Questions Answer
interaction with the dashboard. • Daily Reading Trends
Your answer should focus on usability rather than However:
aesthetics alone. • Some charts use small legends that may be difficult to read.
iii) Evaluate whether the labels, titles, and legends • Percentages are shown but sometimes lack units (e.g.,
used in the dashboard are clear and unambiguous number of users, sales amount).
for first-time users. For first-time users, most labels are understandable, but adding
Support your answer with logical reasoning. clearer units (e.g., “% of students”) would improve clarity.
iv) Assess how effectively the presented charts iv) Effectiveness of Charts for Students
support students in organizing, analyzing, and The charts effectively support students because:
interpreting data. • Bar charts help compare categories easily.
Give a brief justification. • Pie charts show percentage distribution clearly.
v) Recommend one additional type of data that • Line graphs display trends over time.
could be included to make the dashboard more These chart types help students:
meaningful and relatable for students studying • Organize information
data representation. • Analyze trends
• Compare values
• Interpret data visually
Thus, the dashboard is effective for data representation learning.
v) Additional Data Recommendation
One additional useful data type would be:
Average Reading Time per Student
This would help students:
• Understand reading habits
• Compare engagement levels
• Practice interpreting numerical data and averages
Including this would make the dashboard more meaningful and
educational.

Q. 3 Here is the answer according to Class 11 Practical / Exam Format


Using the Insertion Sort method, arrange the following (Step-by-Step Method):
numbers in ascending order.
32, 14, 27, 10, 19, 35 Question:
Show all the steps clearly.
Write the list after each pass of the insertion sort until the list Using Insertion Sort, arrange the following numbers in ascending
is completely sorted. order:

Page 8 of 102
Ser SLO Section Questions Answer
32, 14, 27, 10, 19, 35

Aim:

To sort the given list in ascending order using the Insertion Sort
method.

Insertion Sort Concept (Brief Theory):

Insertion Sort works by dividing the list into two parts:

Sorted part (left side)

Unsorted part (right side)

At each pass, one element from the unsorted part is picked and
placed in its correct position in the sorted part.

Given List:

32, 14, 27, 10, 19, 35

Pass 1:

Compare 14 with 32 and insert in correct position.

Before:
32, 14, 27, 10, 19, 35

After Pass 1:
14, 32, 27, 10, 19, 35

Pass 2:

Insert 27 into sorted part (14, 32)

Page 9 of 102
Ser SLO Section Questions Answer
27 < 32 → shift 32
27 > 14 → place after 14

After Pass 2:
14, 27, 32, 10, 19, 35

Pass 3:

Insert 10 into sorted part (14, 27, 32)

10 < 32 → shift
10 < 27 → shift
10 < 14 → shift

After Pass 3:
10, 14, 27, 32, 19, 35

Pass 4:

Insert 19 into sorted part (10, 14, 27, 32)

19 < 32 → shift
19 < 27 → shift
19 > 14 → place after 14

After Pass 4:
10, 14, 19, 27, 32, 35

Pass 5:

Insert 35 into sorted part (10, 14, 19, 27, 32)

35 > 32 → already in correct position

After Pass 5:
10, 14, 19, 27, 32, 35
Page 10 of 102
Ser SLO Section Questions Answer
Q. 4

Write a Python program that:


• Generates a dataset of two variables x and y, where
y=3x+4y
• Plots:
o A line chart showing the relationship between
x and y
o A box plot for the variable y

Ensure that the plots are clearly labeled.

Q. 5 (For collecting qualitative data about students’ preference for online


i) You are assigned to investigate students’ preference for vs face-to-face learning)
online learning over face-to-face learning. Aim:
Design any four open-ended interview questions that To collect detailed opinions and experiences of students regarding
would help you collect qualitative data about students’ their learning preferences.
learning preferences. Open-Ended Questions:
1. What do you like most about online learning compared to
ii) You are conducting a survey to study students’ reading face-to-face learning?
habits in your class. 2. What challenges do you face during online classes?
Design a closed-ended questionnaire consisting of at 3. How does face-to-face learning help you understand concepts
least four questions suitable for distributing to 50 better or worse than online learning?
students. Each question should offer fixed response 4. In your opinion, which learning method is more effective for
options. you and why?
These questions allow students to answer freely and give detailed
responses.

Page 11 of 102
Ser SLO Section Questions Answer
Aim:
To collect quantitative data about students’ reading habits using fixed
response options.
Questionnaire:
1. How often do you read books (other than textbooks)?
a) Daily
b) Weekly
c) Monthly
d) Rarely
2. What type of books do you prefer to read?
a) Story/Novel
b) Educational/Academic
c) Islamic/Religious
d) General Knowledge
3. How much time do you spend reading daily?
a) Less than 30 minutes
b) 30–60 minutes
c) 1–2 hours
d) More than 2 hours
4. Where do you mostly read?
a) Printed books
b) E-books (PDF)
c) Mobile/Tablet
d) Social Media Articles
Result:
• Open-ended questions help collect detailed opinions
(qualitative data).
• Closed-ended questions help collect measurable data
(quantitative data) from 50 students.

3. A Q No.1. a) def factorial(n):


a) Write a Python program that uses a function to enter fact = 1
a number, find its factorial, and enter numbers until a for i in range(1, n + 1):
negative number is found. fact = fact * i
return fact
while True:
Page 12 of 102
Ser SLO Section Questions Answer
num = int(input("Enter a number: "))

if num < 0:
print("Negative number entered. Program stopped.")
break
else:
print("Factorial of", num, "is", factorial(num))

A Q No.2. i) Most Important Factor for Online Grocery Store:


You want to have an online grocery delivery platform. To
validate your online business idea, it is recommended to The most important factor is ease of use and fast delivery.
develop a Minimum Viable Product (MVP) before you start Customers should be able to easily browse products, place orders,
developing it on a large scale. and receive groceries quickly and reliably.
i. Determine the most important factor for the online
grocery store. ii) Tools and Technologies for Development
ii. List the relevant tools and technology that you would Frontend:
use for the development of Frontend and Backend. • HTML
Once the MVP is created and feedback is collected from • CSS
potential users like friends, relatives, etc., design any • JavaScript
three future improvements that you will make to the • [Link] (for user-friendly interface)
system. Backend:
• Python (Django / Flask)
• Database: MySQL or MongoDB
• APIs for order processing and user management
iii) Three Future Improvements After MVP

1. Online Payment System


o Add debit/credit card and mobile wallet support
2. Real-Time Order Tracking
o Customers can track delivery status live
3. Recommendation System
o Suggest products based on customer purchase history

Page 13 of 102
Ser SLO Section Questions Answer
A a) [12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, 14]
Q No.3. b) 35
You work as a climate analyst, recording the average 12
temperature-Over the course of a year-in degrees Celsius c) sum temperature is incorrect → should be sum(temperature),
for each month. Use Python lists to examine the data. Missing closing bracket ) in print statement.
[10 Marks] Code:
a) temperature = [12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, 14]
Save the following monthly temperatures into a Python list avg = sum(temperature) / 12
and then print the list. print("Average temperature =", avg)
Temperature (°C): Average temperature = 23.75
[12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, 14]
[2 marks] d) temperature = [12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, 14]
b) count = 0
What will the following Python code display? for i in range(12):
temperature = [12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, if temperature[i] > 30:
14]; count = count + 1
print(max(temperature)) print("Total hot months:", count)
print(min(temperature))
[1 + 1 marks]
c)
Consider the following Python program. Analyze for errors
and provide a rewritten, corrected code.
temperature = [12, 15, 18, 22, 28, 32, 35, 34, 30, 25, 20, 14]
avg = sum temperature / 12
print("Average temperature = ", avg
[4 marks]
d)
Modify the following Python program so that it counts and
prints the number of months with high temperature greater
than 30°C. temperature = [12, 15, 18, 22, 28, 32, 35, 34, 30,
25, 20, 14]; count = 0 for i in range(12): if temperature[i] <
30: count = count + 1 print("Total hot months:", count)
A Q No.4. status = input("Has the student returned the book? (returned/not
A school librarian wants to track whether students have returned): ")
returned their library books on time.
if [Link]() == "returned":
Page 14 of 102
Ser SLO Section Questions Answer
i. Write a Python program that asks the user print("Book has been returned.")
whether a student has returned the book or elif [Link]() == "not returned":
not. print("Book has not been returned.")
• If the student has returned the book, print: else:
"Book has been returned." print("Invalid input.")
ii. returned_count = 0
• If the student has not returned the book, print:
"Book has not been returned." for i in range(5):
ii. Modify the program to enter data for five (05) status = input(f"Student {i+1} - Has the book been returned?
students. (returned/not returned): ")

if [Link]() == "returned":
print("Book has been returned.")
returned_count += 1
elif [Link]() == "not returned":
print("Book has not been returned.")
else:
a. print("Invalid input.")
A Here is a prototype for a websites that generates real time 1. Are the labels, colors, and icons in the prototype clear and
results for students favourite subjects. Provide feedback on easy to understand?
how to enhance its design and functionality. Yes, the labels, colors, and icons are mostly clear. Each subject on
the bar chart is labeled. However, the clarity could be improved by:
• Using contrasting colors for better visibility.
• Making sure the icons match the subject (e.g., a paintbrush for
Art).
• Adding a legend for the pie chart if it’s not already included.

2. What changes could make the prototype more engaging for


students?
• Are the labels, colors, and icons in the prototype clear
• Add interactive elements like hovering over bars or pie slices
and easy to understand?
to show exact numbers.
• What changes could make the prototype more engaging
• Include animations or transitions when switching between
for students?
charts.
• If you could add another type of chart or data, what • Allow students to filter data by grade, gender, or other
would it be, and why? categories.

Page 15 of 102
Ser SLO Section Questions Answer
• Do you think this chart would help students learn about 3. If you could add another type of chart or data, what would it
organizing and interpreting data? Explain your answer. be, and why?
• How could this prototype be used in a classroom • Line graph: To show how subject preferences have changed
discussion about student interests? over time if multiple surveys are done each year.
• Stacked bar chart: To compare subject preference by grade
or gender more clearly.
4. Do you think this chart would help students learn about
organizing and interpreting data? Explain your answer.
Yes. The bar and pie charts allow students to:
• See data visually, making it easier to understand.
• Compare quantities between categories (e.g., Math vs. Art).
• Analyze trends or patterns in student preferences.
5. How could this prototype be used in a classroom discussion
about student interests?
• Students could predict which subjects would be most or least
popular before revealing the charts.
• The data could lead to discussions about why certain subjects
are more popular.
• Students could propose ways to make less popular subjects
more interesting.

B Q No.1. Step 1: START


Develop a pseudocode that prints all odd numbers from 1 to Step 2: FOR num FROM 1 TO 50 DO
50. Step 3: IF num MOD 2 ≠ 0 THEN
Step 4: PRINT num
Step 5: END IF
Step 6: END FOR
Step 7: END
B Q No.2.
Draw a trace table for the following pseudocode: step i a b result Explanation
Step 1: START 2 - 2 5 - Initialize a= 2, b= 5
Step 2: a ← 2, b ← 5 3 - 2 5 1 Initialize result = 1
Step 3: result ← 1 4 1 2 5 1 Loop starti = 0
Step 4: FOR i FROM 1 TO b DO 5 1 2 5 2 result = 1 × 2 = 2
Step 5: result ← result × a 4 2 2 5 2 Loop next iteration, i = 2
Step 6: END FOR
Page 16 of 102
Ser SLO Section Questions Answer
Step 7: PRINT result 5 2 2 5 4 result = 2 × 2 = 4
Step 8: END 4 3 2 5 4 Loop next iteration, i = 3
5 3 2 5 8 result = 4 × 2 = 8
4 4 2 5 8 Loop next iteration, i = 4
5 4 2 5 16 result = 8 × 2 = 16
4 5 2 5 16 Loop next iteration, i = 5
5 5 2 5 32 result = 16 × 2 = 32
6 - 2 5 32 Loop ends (i > b)
7 - 2 5 32 Print result = 32
B Q No.3.
Write a Python program to generate a dataset for the
equation y = 2x² + 1 for x values from 1 to 10 and plot:
• A line graph
• A histogram

B Q No.4. Survey Topic: Students’ Daily Screen Time Habits


You are conducting a survey to analyze students’ daily (Target: 40 Students)
screen time habits. 1. How many hours do you spend on screens daily?
Design a questionnaire with at least four closed-ended ☐ Less than 2 hours
questions to collect data from 40 students. ☐ 2–4 hours
☐ 5–7 hours
☐ More than 7 hours

Page 17 of 102
Ser SLO Section Questions Answer
2. What device do you use most frequently?
☐ Smartphone
☐ Laptop
☐ Tablet
☐ Desktop Computer
3. Do you use screens mainly for study purposes?
☐ Yes
☐ No
Do you take regular breaks while using screens?
☐ Always
☐ Sometimes
☐ Never
B Q No.5. Why Students Prefer Mobile Apps Over Textbooks
You are assigned to investigate why students prefer using 1. What features of mobile apps make learning easier for you?
mobile apps for studying instead of textbooks. 2. How do mobile apps improve your understanding compared to
Write any four open-ended interview questions to collect textbooks?
qualitative data. 3. Can you describe your experience using mobile apps for
studying?
4. What challenges do you face while using textbooks that
mobile apps solve?

4. . Write and execute Part 1 Q.1: Write a Python program to input two numbers from # Input two numbers
simple programs that the user and display their sum. num1 = int(input("Enter first number: "))
uses variables and num2 = int(input("Enter second number: "))
operators with input/ # Perform addition
output handling in sum = num1 + num2
Python. # Display result
print("Sum =", sum)
Sectio
nA
Q.2: Write a Python program to calculate the area of a # Input length and width
rectangle using length and width entered by the user. length = float(input("Enter length: "))
width = float(input("Enter width: "))

# Calculate area
Page 18 of 102
Ser SLO Section Questions Answer
area = length * width

# Display result
print("Area of rectangle =", area)
Q.3: Write a Python program to calculate Simple Interest # Input values
using the formula: P = float(input("Enter Principal amount: "))
SI = (P × R × T) / 100 R = float(input("Enter Rate of interest: "))
T = float(input("Enter Time (years): "))

# Calculate simple interest


SI = (P * R * T) / 100

# Display result
print("Simple Interest =", SI)
Q.4 : Write a Python program to check whether a number # Input number
entered by the user is even or odd. num = int(input("Enter a number: "))
# Check even or odd
if num % 2 == 0:
print("The number is Even")
else:
print("The number is Odd")
Q.5: Write a Python program to input three numbers and # Input three numbers
calculate their average. a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

# Calculate average
average = (a + b + c) / 3

# Display result
print("Average =", average)
➢ Write and execute Q.1: Write a Python program to input a number N and # Input number
programs in Python calculate the sum of first N natural numbers. n = int(input("Enter a number: "))
that using
sequence, # Initialize sum
total = 0
Page 19 of 102
Ser SLO Section Questions Answer
selection, and
repetition. # Repetition using for loop
for i in range(1, n + 1):
total = total + i

# Display result
print("Sum of first", n, "natural numbers =", total)
Q.2: Write a Python program to input a number and check # Input number
whether it is positive, negative, or zero. num = int(input("Enter a number: "))

# Selection using if-elif-else


if num > 0:
print("Number is Positive")
elif num < 0:
print("Number is Negative")
else:
print("Number is Zero")
Q.3: Write a Python program to display all even numbers # Input number
from 1 to N. n = int(input("Enter the value of N: "))

# Repetition with selection


for i in range(1, n + 1):
if i % 2 == 0:
print(i)
Q.4: Write a Python program to display the multiplication # Input number
table of a number entered by the user. num = int(input("Enter a number: "))

# Loop for table


for i in range(1, 11):
print(num, "x", i, "=", num * i)
Q.5 Write a Python program that asks the user to enter a # Predefined password
password. If the password is incorrect, ask again until the password = "python123"
correct password is entered.
# Repetition with selection
while True:
user_input = input("Enter password: ")
Page 20 of 102
Ser SLO Section Questions Answer

if user_input == password:
print("Access Granted")
break
else:
print("Wrong Password, Try Again")
➢ Draw different Q.1: Write a Python program to draw a square using the import turtle
shapes using Turtle Turtle library. t = [Link]()
library functions in # Draw square
Python. for i in range(4):
[Link](100)
[Link](90)

[Link]()
Q.2: Write a Python program to draw a rectangle using the import turtle
Turtle library. t = [Link]()

# Draw rectangle
for i in range(2):
[Link](150)
[Link](90)
[Link](80)
[Link](90)
[Link]()
Q.3: Write a Python program to draw an equilateral triangle import turtle
using the Turtle library.
t = [Link]()

# Draw triangle
for i in range(3):
[Link](120)
[Link](120)

[Link]()

Page 21 of 102
Ser SLO Section Questions Answer
Q4: Write a Python program to draw a circle using the Turtle import turtle
library.
t = [Link]()

# Draw circle
[Link](70)

[Link]()

Q5: Write a Python program to draw a star using the Turtle import turtle
library.
t = [Link]()

# Draw star
for i in range(5):
[Link](150)
[Link](144)

[Link]()

➢ Write programs in Q.1: Write a Python program to calculate the square root and import math
Python using factorial of a number using the math library. num = int(input("Enter a number: "))
different libraries. print("Square Root =", [Link](num))
print("Factorial =", [Link](num))
Q.2: Write a Python program to generate a random number import random
between 1 and 100 by using random library.
random_number = [Link](1, 100)
print("Random Number:", random_number)increase (positive
relationship).
Q3: Write a Python program to display the current date and import datetime
time by using datetime library. current_datetime = [Link]()
print("Current Date and Time:", current_datetime)

Page 22 of 102
Ser SLO Section Questions Answer
Q4: Write a Python program to calculate the mean and import statistics
median of a list of numbers by using statistics library. data = [10, 20, 30, 40, 50]

print("Mean =", [Link](data))


print("Median =", [Link](data))
Q5: Write a Python program to display the current working import os
directory by using os library. current_directory = [Link]()
print("Current Working Directory:", current_directory)

Page 23 of 102
Ser SLO Section Questions Answer
➢ Write and execute Q1: Write a Python program using functions to calculate total # Function to calculate total marks
Python programs marks, percentage, and grade of a student. def calculate_total(marks):
using function that return sum(marks)
solves a large # Function to calculate percentage
problem by def calculate_percentage(total, subjects):
decomposing into return total / subjects
sub problems. # Function to calculate grade
def calculate_grade(percentage):
if percentage >= 80:
return "A"
elif percentage >= 60:
return "B"
elif percentage >= 40:
return "C"
else:
return "Fail"
# Main program
marks = []
subjects = int(input("Enter number of subjects: "))

for i in range(subjects):
m = int(input(f"Enter marks of subject {i+1}: "))
[Link](m)
total = calculate_total(marks)
percentage = calculate_percentage(total, subjects)
grade = calculate_grade(percentage)
print("Total Marks =", total)
print("Percentage =", percentage)
print("Grade =", grade)

Page 24 of 102
Ser SLO Section Questions Answer
Q2: Write a Python program using functions to perform # Function to deposit amount
deposit, withdraw, and balance check operations. def deposit(balance, amount):
return balance + amount
# Function to withdraw amount
def withdraw(balance, amount):
if amount > balance:
print("Insufficient Balance")
return balance
else:
return balance - amount
# Function to display balance
def show_balance(balance):
print("Current Balance =", balance)
# Main program
balance = 5000
amt = int(input("Enter amount to deposit: "))
balance = deposit(balance, amt)
amt = int(input("Enter amount to withdraw: "))
balance = withdraw(balance, amt)
show_balance(balance)

Page 25 of 102
Ser SLO Section Questions Answer
Q3: Write a Python program using functions to perform basic # Arithmetic functions
arithmetic operations. def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Division not possible"
return a / b
# Main program
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Addition =", add(x, y))
print("Subtraction =", subtract(x, y))
print("Multiplication =", multiply(x, y))
print("Division =", divide(x, y))
Q4: Write a Python program using functions to calculate # Function to calculate allowances
gross salary and net salary of an employee. def calculate_allowances(basic):
hra = basic * 0.20
da = basic * 0.10
return hra + da
# Function to calculate deductions
def calculate_deductions(basic):
tax = basic * 0.05
return tax
# Main program
basic_salary = float(input("Enter basic salary: "))
allowances = calculate_allowances(basic_salary)
deductions = calculate_deductions(basic_salary)
gross_salary = basic_salary + allowances
net_salary = gross_salary - deductions
print("Gross Salary =", gross_salary)
print("Net Salary =", net_salary)

Page 26 of 102
Ser SLO Section Questions Answer
Q5: Write a Python program using functions to check # Function to check prime
whether a number is prime and to find its factorial. def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# Function to calculate factorial
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
# Main program
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a Prime number")
else:
print(num, "is not a Prime number")
print("Factorial =", factorial(num))
• Write Python Q1: Write a Python program that accepts a number as an # Function to calculate square and cube
programs that argument and calculates its square and cube. def square_cube(n):
performs some print("Square =", n * n)
mathematical print("Cube =", n * n * n)
operations on a
value passed to it. # Main program
num = int(input("Enter a number: "))
square_cube(num)

Page 27 of 102
Ser SLO Section Questions Answer
Q2: Write a Python program that accepts a number as a # Function to calculate factorial
parameter and finds its factorial. def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
# Main program
num = int(input("Enter a number: "))
print("Factorial =", factorial(num))
Q3: Write a Python program that accepts a number and # Function to check even or odd
checks whether it is even or odd. def check_even_odd(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"
# Main program
num = int(input("Enter a number: "))
result = check_even_odd(num)
print("The number is", result)
Q4: Write a Python program that accepts a number and # Function to calculate sum of digits
calculates the sum of its digits. def sum_of_digits(n):
total = 0
while n > 0:
digit = n % 10
total = total + digit
n = n // 10
return total
# Main program
num = int(input("Enter a number: "))
print("Sum of digits =", sum_of_digits(num))

Page 28 of 102
Ser SLO Section Questions Answer
Q5: Write a Python program that accepts two numbers and # Function to find maximum
returns the maximum number. def find_max(a, b):
if a > b:
return a
else:
return b
# Main program
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

print("Maximum number =", find_max(x,y))


➢ Write programs in Q1: Write a Python program to take user input and store it in # Open file in write mode
Python using file a text file. file = open("[Link]", "w")
handling and name = input("Enter student name: ")
databases. roll = input("Enter roll number: ")
[Link]("Name: " + name + "\n")
[Link]("Roll No: " + roll)
[Link]()
print("Data written to file successfully")
Q2: Write a Python program to read and display contents of # Open file in read mode
a text file. file = open("[Link]", "r")
content = [Link]()
print("File Contents:\n", content)
[Link]()
Q3: Write a Python program to add new data into an existing # Open file in append mode
file without deleting old data. file = open("[Link]", "a")
course = input("Enter course name: ")
[Link]("\nCourse: " + course)
[Link]()
print("Data appended successfully")

Page 29 of 102
Ser SLO Section Questions Answer
Q4: Write a Python program to create a database and insert import sqlite3
student records using SQLite. # Connect to database
conn = [Link]("[Link]")
cursor = [Link]()
# Create table
[Link]("""
CREATE TABLE IF NOT EXISTS student (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
""")
# Insert record
[Link]("INSERT INTO student (name, marks) VALUES (?,
?)",
("Ali", 85))
[Link]()
[Link]()
print("Record inserted successfully")
Q5: Write a Python program to retrieve and display records import sqlite3
from a database table. # Connect to database
conn = [Link]("[Link]")
cursor = [Link]()
# Fetch records
[Link]("SELECT * FROM student")
records = [Link]()
# Display records
for row in records:
print("ID:", row[0], "Name:", row[1], "Marks:", row[2])
[Link]()
• Write and execute Q1: Write a Python program to create a list of five numbers # Create list
programs in Python and display its elements. numbers = [10, 20, 30, 40, 50]
using lists. # Display list elements
for num in numbers:
print(num)

Page 30 of 102
Ser SLO Section Questions Answer
Q2: Write a Python program to find the sum and average of # Create a list
elements in a list. numbers = [5, 10, 15, 20, 25]
# Calculate sum and average
total = sum(numbers)
average = total / len(numbers)
print("Sum =", total)
print("Average =", average)
Q3: Write a Python program to find the largest and smallest # Create a list
elements in a list. numbers = [12, 45, 2, 89, 34]
# Find max and min
print("Maximum =", max(numbers))
print("Minimum =", min(numbers))
Q4: Write a Python program to search an element in a list # Create list
and display whether it exists or not numbers = [10, 20, 30, 40, 50]
# Input element to search
search = int(input("Enter number to search: "))
if search in numbers:
print("Element found in the list")
else:
print("Element not found in the list")
Q5: Write a Python program to add an element to a list and # Create list
remove an element from the list. numbers = [1, 2, 3, 4, 5]
# Add element
[Link](6)
print("List after adding:", numbers)
# Remove element
[Link](3)
print("List after removing:", numbers)
5. ➢ Create and test a Q1: Mini Shop Prototype Task:
basic prototype for • Design a small prototype for a local shop (e.g., stationery,
business idea. grocery).
• Decide what items you will sell, their prices, and display
method.
• Test: Ask friends/family to “buy” items from your prototype
using paper mock-ups or a simple spreadsheet.

Page 31 of 102
Ser SLO Section Questions Answer
• Iterate: Based on feedback, change item prices, add/remove
items, or improve display.
Goal: Simulate a sales and pricing model for a shop.

Q2: Online Service Booking Prototype Task:


• Create a prototype for a service business (e.g., home
cleaning, tutoring, salon).
• Decide: services offered, pricing, booking method (e.g., paper
forms, spreadsheet, or Google Form).
• Test: Let classmates or family book a service.
• Iterate: Update service options, timing, or pricing based on
test experience.
Goal: Understand service flow and customer booking
experience.

Q3: Customer Feedback Prototype Task:


• Design a simple way to collect customer feedback for a
product or service.
• Use sticky notes, Google Forms, or paper forms.
• Test: Ask users to give feedback and observe their
responses.
• Iterate: Modify questions or method of collection to get better
or more useful feedback.
Goal: Learn to gather customer insights for improving a product or
service.

Q4: Food Delivery Prototype Task:


• Create a prototype for a small-scale food delivery business
(e.g., sandwiches, juices).
• Decide menu, prices, delivery method, and order tracking.
• Test: “Take orders” from classmates using forms or mock
apps, and simulate delivery.
• Iterate: Improve delivery speed, menu clarity, or pricing based
on testing.
Goal: Test logistics and order management.

Page 32 of 102
Ser SLO Section Questions Answer
Q5: Mini E-commerce Prototype Task:
• Design a prototype for an online store selling a product of your
choice.
• Decide product details, payment method (mock payment), and
delivery tracking.
• Test: Use a simple spreadsheet or form for “orders” and track
mock inventory.
• Iterate: Adjust product descriptions, pricing, or order workflow
based on test results.
Goal: Learn how a digital business works and how prototypes help
improve it.

• Create and test a Q1: MVP for an Online Store Task:


basic minimum • Front-end: Design a simple landing page showing products
viable product for using a tool like Figma, Canva, or Google Slides. Include
the business. product name, image, and price.
• Back-end: Use Google Sheets or Airtable as a simple
database to store product info and stock.
• Test: Ask 5–10 users to “browse” products and place mock
orders. Record their experience.
• Iterate: Update layout, product descriptions, or prices based
on feedback.
Goal: Test core shopping and user experience with minimal setup.

Q2: MVP for Online Tutoring Platform Task:


• Front-end: Create a basic signup/login page and class
schedule page using Google Forms, Slides, or Canva
prototypes.
• Back-end: Use Google Sheets to track enrolled students and
their booked sessions.
• Test: Invite a few classmates for a free trial session and
collect feedback on usability and clarity.
• Iterate: Adjust signup flow, schedule visibility, or session
duration based on feedback.
Goal: Validate booking and scheduling workflow before full
development.
Page 33 of 102
Ser SLO Section Questions Answer
Q3: MVP for Food Delivery Service Task:
• Front-end: Create a simple menu interface using slides or a
low-code tool (e.g., Glide App, Google Forms).
• Back-end: Track orders and delivery status using Google
Sheets or Excel.
• Test: Take orders from classmates/family and simulate
delivery. Note timing, packaging, and order accuracy.
• Iterate: Update menu, delivery process, or order management
system.
Goal: Test operational workflow with minimal investment.
Q4: MVP for Handmade Products E-Commerce Task:
• Front-end: Make a catalog page showcasing products
(image + description + price) using Figma or Canva.
• Back-end: Use a spreadsheet or Airtable to track inventory
and orders.
• Test: Show the catalog to potential customers, take mock
orders, and ask for feedback on usability and pricing.
• Iterate: Adjust product presentation, pricing, or ordering
process.
Goal: Validate product-market fit with minimal production.
Q5: MVP for a Digital Platform / App Task:
• Front-end: Build a clickable prototype for your app using
Figma, Canva, or Google Slides, including only the core
feature (e.g., booking, payment, messaging).
• Back-end: Simulate data storage with Google Sheets or
Airtable for users, orders, or messages.
• Test: Have users navigate your prototype and try the main
feature. Record their feedback.
• Iterate: Improve layout, navigation, or workflow based on user
testing.
Goal: Validate core functionality before building a fully coded app.
6. [SLO CS-11-A-01] B Q.1 Final Simplified Answer (Using K-Map):
Simplify the Boolean Function F using the Karnaugh Map F=A+B+C̅
and also construct the logic circuit for the simplified
expression.
F = A̅B̅C̅+ A̅BC̅+ A̅BC+ AB̅C̅ + AB̅C+ ABC̅ + ABC
Page 34 of 102
Ser SLO Section Questions Answer

Q.2 Simplify the Boolean Function F using the Karnaugh Final Simplified Answer (Using K-Map):
Map. F=C
F=A̅B̅C+A̅BC+AB̅C+ABC
Q.3 Simplify the Boolean Function F using the Karnaugh Final Simplified Answer (Using K-Map):
Map F=A̅B̅C̅+A̅BC̅+AB̅C̅+ABC̅ F=C̅
Q.4 Draw truth table of (A.B)+C (A.B)+C
0
1
0
1
0
1
1
1
7. [SLO CS-11-B-01] B Q.1 Create pseudocode to Print the largest/smallest num1 = [number]
number. num2 = [number]

IF num1 > num2 THEN


PRINT "Largest: " + num1
PRINT "Smallest: " + num2
ELSE
PRINT "Largest: " + num2
PRINT "Smallest: " + num1
Q.2 Create pseudocode to Print even/odd numbers. num = [number]

IF num MOD 2 == 0 THEN


PRINT num + " is even"
ELSE
PRINT num + " is odd"
Q.3 Create pseudocode to Find the factorial of a number. n = [number]
fact = 1
i=1

WHILE i <= n
Page 35 of 102
Ser SLO Section Questions Answer
fact = fact * i
i=i+1

PRINT "Factorial: " + fact


Q.4 Create pseudocode to Print the table of a number. n = [number]
i=1

WHILE i <= 10
PRINT n + " x " + i + " = " + (n * i)
i=i+1
8. [SLO CS-11-B-02] B Q1. Search a given number from the list of numbers by 1. Sort the list
using binary search. 2. Find middle element
3. Compare target with middle
4. Repeat steps 2-3 in half of the list
Q2. Search a given number from the list of numbers by 1. Sort the list
using Linear search. 2. Find the middle element
3. Compare the target with the middle element
4. If match, return the position
5. If target is less than middle, repeat steps 2-4 in the left half
6. If target is greater than middle, repeat steps 2-4 in the right half
7. Continue until found or not found
Q3. Sort the list of numbers using Bubble sort. 1. Compare adjacent elements
2. If elements are in wrong order, swap them
3. Repeat steps 1-2 until no more swaps needed
Q.4 Sort the list of numbers using Insertion sort. 1. Iterate through the list starting from the second element
2. Compare the current element with the previous elements
3. Shift larger elements to the right
4. Insert the current element at its correct position
5. Repeat steps 1-4 until the list is sorted
9. [SLO CS-11-G-01] B Q1. Design a strategy for collecting data from real-life - Identify target audience
examples using: Interviews - Prepare open-ended questions
- Conduct face-to-face or online interviews
- Record and analyze responses
Q2. Design a strategy for collecting data from real-life - Create online or paper-based questionnaires
examples using: Surveys - Share with target audience
- Collect and analyze responses
Page 36 of 102
Ser SLO Section Questions Answer
Q3. Design a strategy for collecting data from real-life - Develop a prototype or mockup
examples using: Prototypes - Test with users
- Gather feedback and iterate
Q4. Design a strategy for collecting data from real-life - Create a simulated environment
examples using: Simulations - Test with users
- Observe and record behavior
10. [SLO CS-11-D-03] B Q1. Scatter Plot: The scatter plot shows a random distribution of points, indicating no
clear linear relationship between X and Y.
import [Link] as plt
import numpy as np

# Sample data
x = [Link](10)
y = [Link](10)

[Link](x, y)
[Link]('X')
[Link]('Y')
[Link]('Scatter Plot Example')
[Link]()

What is the relationship between X and Y?


Q2. What is the range of X values? The X values range from approximately 0 to 1.
Q3. What is the median Y value? To answer this, we would need to calculate the median of the Y
values: [Link](y).
Q4. Are there any outliers in the data? Visually inspecting the plot, there don't appear to be any obvious
outliers.
11. [SLO CS-12-C-02] A Q1. Write a Python program to create a text file named # Open the file in write mode
"[Link]" and write the following lines to it with open("[Link]", "w") as file:
Hello, World! # Write the lines to the file
This is a test file. [Link]("Hello, World!\n")
Python is fun! [Link]("This is a test file.\n")
[Link]("Python is fun!\n")
Q2. Trace output: fruits = ["Apple", "Banana", "Cherry"] ['Apple', 'Elderberry', 'Banana', 'Cherry', 'Date']
[Link]("Date") ['Apple', 'Elderberry', 'Cherry', 'Date']
[Link](1, "Elderberry")
Page 37 of 102
Ser SLO Section Questions Answer
print(fruits)
[Link]("Banana")
print(fruits)
Q3. How do you establish a connection to a SQLite import sqlite3
database using Python? conn = [Link]('[Link]')
Q4. def math_operations(num):
Write Python programs that performs some mathematical print("Number:", num)
operations on a value passed to it. print("Square:", num ** 2)
print("Cube:", num ** 3)
print("Square Root:", num ** 0.5)
math_operations(5)
12. [SLO CS-12-C-03] A Q1. Create a nested list of fruits and print the second fruit in fruits = [["Apple", "Banana", "Cherry"], ["Date", "Elderberry", "Fig"]]
the second list. print(fruits[1][1]) # Output: Elderberry
Q2. Create a dictionary with a list as a value and print the person = {"name": "John", "hobbies": ["reading", "swimming",
second item in the list. "cycling"]}
print(person["hobbies"][1]) # Output: swimming
Q3. What is the output of the following code? swimming
person = {"name": "John", "hobbies": ["reading",
"swimming", "cycling"]}
print(person["hobbies"][1])
Q4. What is the output of the following code? Quetta
cities = [["Lahore", "Karachi", "Islamabad"], ["Peshawar",
"Quetta", "Multan"]]
print(cities[1][1])
13. [SLO CS-12-C-04] A Q1. Write a unit test for the add_numbers (a, b) function to import unittest
verify that it correctly adds two positive numbers.
def add_numbers(a, b):
return a + b

class TestAddNumbers([Link]):
def test_add_positive_numbers(self):
result = add_numbers(2, 3)
[Link](result, 5)

if __name__ == '__main__':
[Link]()
Page 38 of 102
Ser SLO Section Questions Answer
Q2. how can you use print statements to identify the def calculate_average(numbers):
problem in calculate_average(numbers) function? sum = 0
for num in numbers:
def calculate_average(numbers): print("num:", num)
sum = 0 sum = num
for num in numbers: print("sum:", sum)
sum = num average = sum / len(numbers)
average = sum / len(numbers) return average
return average

numbers = [1, 2, 3, 4, 5]
print(calculate_average(numbers))
Q3. What would be the output of the following code? The output would be Error: non-numeric input: 3

numbers = [1, 2, '3', 4, 5]


print(calculate_average(numbers))
Q4. Examine the following Python program, identify any Errors identified and corrected:
errors, and correct them.
rainfall=[50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65] 1. Missing closing quote in the print statement: added a closing quote
avg= sum(rainfall)/12; after "average rainfall ="
print("average rainfall = , average) 2. Missing comma in the print statement: added a comma after
"average rainfall =" to separate the string from the variable avg
3. Hardcoded the divisor (12) in the average calculation: replaced 12
with len(rainfall) to make the code more flexible and accurate, in case
the length of the rainfall list changes in the future.
Corrected:
rainfall = [50, 80, 60, 30, 120, 90, 70, 100, 85, 95, 40, 65]
avg = sum(rainfall) / len(rainfall)
print("average rainfall =", avg)
14. Students will be able to A Q1. Draw a truth table for a 3 input NAND gate? Premier PBA Computer Science HSSC
learn about Logic
Gates, Truth Tables, K Q2. Draw a logic gate for the Boolean function: NBF, Text Book, Grade 11, pg .11
Maps F (x, y) = x . y + x . y

Q 3. Give the Boolean identity for the following identity NBF, Text Book, Grade 11, pg .12
types?
Page 39 of 102
Ser SLO Section Questions Answer
Complement Law(AND), Absorption Law(AND), Associative
Law(OR)

Q4. Simplify the following function by using K map NBF, Text Book, Grade 11, pg .64

F = ( A . B . C )+ ( A . B . C )+ ( A . B . C )+
(A.B .C)

15. Students will be able to A Q 1. Draw a flow chart / Pseudo code to print factorial of a Premier PBA Computer Science HSSC, pg. 91
draw Flow chart / write number?
Pseudo code to
address Q 2. Draw a flow chart / Pseudo code that inputs 3 numbers Premier PBA Computer Science HSSC, pg. 93
Computational and prints the largest ?
Problems
Q 3. Draw a trace table for the following pseudo code? NBF, Text Book, Grade 11, pg . 80
1. number = 3
2. PRINT number
3. FOR i from 1 to 3:
4. number = number + 5
5. PRINT number
6. PRINT “ ? ”

Q 4. Write a bubble sort algorithm of ascending order for Premier PBA Computer Science HSSC, pg. 96
given list?
List = [ 5 , 1 , 4 , 2 , 8 ]

16. Understand the A 1. Write and execute simple programs that use variables FBISE Text Book
importance of computer and operators with input/output handling in Python.
programming and
applications 2. Write and execute a Python program that takes two
numbers as input from the user Performs addition,
subtraction, multiplication, and division. Displays the result
of each operation clearly

Students should be 3. Write Python programs that performs some mathematical


able to write and operations on a value passed to it.
Page 40 of 102
Ser SLO Section Questions Answer
execute simple 4. Write and execute simple programs that uses variables
programs in Python. and operators with input/ output handling in Python.

[Link] a Python program to ask whether 5 employees are


present or absent, count the total present employees, and
display the attendance percentage..

Draw shapes using 6. Write a Python program using the Turtle library to draw a
Turtle Graphics square and a triangle. Use different colors for each shape
functions in Python
7. Write a Python program using the Turtle library to draw a
rectangle and a circle. Use different colors for each shape.

8. Draw different shapes using Turtle library functions in


Python.

9. Write a Python program using the Turtle library to draw an


equilateral triangle and a pentagon. Use different pen colors
for each shape.

Understand the need 10. Write programs in Python using different libraries.
for libraries and use 11. write a Python program using the random library to
simple libraries in generate a random number between 1 and 10 and display it.
Python Explain why the random library is used.
12. Write a Python program using the datetime library to
display the current time only (hours, minutes, and seconds).

[Link] a Python program using the datetime library to


display the current date and time.

Translate simple 14. Write a Python program that takes a number from the
algorithms using user uses selection statement to check whether the number
sequence and is even or odd
repetition in Python [Link] and execute programs in Python that using
sequence, selection, and repetition.

Page 41 of 102
Ser SLO Section Questions Answer
16. Write a Python program that asks the user whether a
student is late or on time and prints an appropriate
message.
17. Write Python programs that performs some
mathematical operations on a value passed to it.

Decompose a problem 18. Write and execute Python programs using function that
into sub-problems and solves a large problem by decomposing into sub problems
implement them
19. Write a Python program that Uses functions to solve a
problem. One function calculates the area of a rectangle.
Another function calculates the perimeter of a rectangle. Call
both functions from the main program

20. Write a Python program that demonstrates how a


problem is decomposed into functions in a real-life scenario
(student result system). One function inputs marks, another
calculates percentage, and a third displays the result.

21. Write a Python program that uses a function to input a


number, cube it, and continue reading numbers until the
user enters zero.

17. Understand the need for A 1. Analyze the following program and identify: (a) Which FBISE Text Book
libraries and use simple library is used (b) Purpose of the library (c) Output if input is
libraries in Python 9
Students will determine 2. What will the output of the following Python code be?
ways of debugging their scores=[45, 60, 55, 70, 80, 65, 75, 85, 50, 90, 40, 68]
code in Python print(max(scores))
.print(min(scores))

3. Identify and correct the errors in the following Python


program. scores=[45, 60, 55, 70, 80, 65, 75, 85, 50, 90, 40,
68]
average = sum(scores)/12
print("Average Score = ", average.
Page 42 of 102
Ser SLO Section Questions Answer
4. .You are a sports teacher tracking the scores of a student
in 12 matches using Python lists.
Store the scores in a Python list and print it. Use the
following data: [45, 60, 55, 70, 80, 65, 75, 85, 50, 90, 40, 68]

5. Write a python code to generate a dataset with two


variables where y=3x+4 and plot a line chart and a box plot.

Students will be able to 6. Write a Python program to generate a dataset where y =


relate the role and x², and visualize the data using a line chart and a box plot.
importance of model
building with their real- 7. Create a line graph using pre-existing temperature data of
world applications a city for 7 days to explain the importance of model building
in understanding real-world trends.

Students will 8. Write a Python program to record daily sales of a shop for
understand and 7 days and display the data using a line graph. Explain how
explain model building helps shopkeepers.
experimental
design in data 9. Write a Python program to design an experiment where
science student study hours and marks are recorded and displayed
using a scatter plot.

10. Write a Python program to generate students’


attendance percentages and display them using a box plot.

Students will 11. Write a Python program to design an experiment where


analyze exercise time and calories burned are recorded and
preexisting data displayed using a scatter plot.
sets to create
summary statistics 12. Create a bar chart using Python to represent the marks
and data visuals of five students in a subject and explain how model building
(such as bar helps in decision making.
charts, pie charts,
line graphs, etc.)

Page 43 of 102
Ser SLO Section Questions Answer
18. Students will be A 1. Identify two applications of block chain technology that FBISE Text Book
able to analyze could be implemented in Pakistan but are not discussed in
and apply the textbook.
concepts of [Link] why these applications are needed and what
blockchain improvements they can bring.
technology and [Link] five reasons why data privacy issues may arise
data privacy in among stakeholders in organizations in Pakistan.
real-world
situations in 4. Explain data anonymization and data minimization with
Pakistan. appropriate examples.

5. Divide the class into two groups to discuss a conflict


between data sharing and data privacy.
One group should argue that social media companies
should share user data with the government to prevent
terrorism, while the other group should argue that this
practice violates privacy rights.
This activity will help students develop communication,
collaboration, and critical thinking skills.
19. Students will be able to: A 1. Imagine you want to track plant growth overtime .How Questions From Official NBF Textbook pg 202
• Plan and design would you design a system to collect data on this ?
a data collection
system

Students will be able to [Link] a survey form to get collected data about the
perform: topic”How economic conditons of various countries are
• Advanced affected by the COVID -19 “?
searches to
locate
information
Design data collection
approach to gather
orginal data

Page 44 of 102
Ser SLO Section Questions Answer
Students will be able to [Link] are assigned to explore the reasons behind students' Questions from Official PBA Model Paper
to: preferences for online learning compared to in-person Premier PBA Computer Science HSSC
Design open-ended learning. What kind of questions would you ask in your
interview questions to interview to gather qualitative data on students' learning
collect qualitative data preferences (any four questions)?

Students will 2. You are conducting a survey to understand students'


understand that how to reading habits. Distribute the survey to 50 students in your
: class. Design a questionnaire having at least four
Design data collection appropriate questions to collect data about students' reading
approach to gather habits with closed ended questions.
borignal data gather
orginal data.
20. Students will be able to A Q 1. Develop a prototype for a smart home, provide Premier PBA Computer Science HSSC, pg. 69
develop Prototype for feedback on how to enhance its design and functionality?
business idea
Q 2. Develop a prototype for an online book store, provide Premier PBA Computer Science HSSC, pg. 70
feedback on how to enhance its design and functionality?
Q 3. You are an entrepreneur and want to start an online T
Shirts store, your goal is to create an MVP( minimum viable
product) to quickly test your idea with potential customers

Students will be able to Q 3. You are an entrepreneur and want to start an online T Premier PBA Computer Science HSSC, pg. 76
learn about Minimum Shirts store, your goal is to create an MVP( minimum viable
Viable Product (MVP) product) to quickly test your idea with potential customers

Students will be able to Q 4. Develop ideas about what your college could do to NBF, Text Book, Grade 11, Lab activity 1 ,
develop create a culture of entrepreneurship on your campus or in pg . 220
Business idea community?

21. Student Should be able B 1. Why multi-factors authentication is more secure than FBISE Text Book
to use protection simple password.
methods.

Page 45 of 102
Ser SLO Section Questions Answer
Student Should be able 2. Why is consistency important in user interface design?
to understand
importance interface of
system.
Student Should be able 3. Describe one common usability issue and suggest a
to understand about practical solution.
usability of interface.
Student Should be able 4. Why is error prevention better than just showing error
to solve errors before message?
compilation.
Student Should be able 5. Why should designer test system with real users before
to test software and launching?
importance of
deployment.
22. Student Should be able B [Link] the concept of computational thinking and FBISE Text Book
to solve complex algorithm design.
problems with quick
and accurate solutions.
Student Should be able 2. Write an algorithm to insert an element at the beginning
to apply logic gates and and at the end of a list. Also, explain the time complexity of
understand their both operations.
functions.
Student Should be able 3. Given the expression: (A + B) * (C - D) a) Show how a
to understand memory stack is used to check whether the parentheses are
locations, and in or out balanced. b) Write the stack operations (Push/Pop) step by
from memory. step.

Student Should be able 4. A printer processes print jobs in the order they are
to understand trees in received. a) Which data structure is most suitable for this
data structure. Manage situation? Why? b) Write an algorithm for enqueue and
order of tree according dequeue operations in a queue.
to problem.
Student Should be able 5. Write the Preorder, Inorder, and Postorder traversal
to understand sequences.
phases of complex
problem.
Page 46 of 102
Ser SLO Section Questions Answer
• Abstraction
• Decomposition
• Pattern
recognition
Algorithm design
23. Student Should be able B [Link] a program that reads five marks in list and find FBISE Text Book
to use more advanced average and maximum marks. 3. Create a class Student
programming construct with the following attributes: • name • roll_no • marks
like lists in python. Include a method to calculate grade based on marks. Create
two objects and display their details and grades .

Student Should be able 2. Write a Python function calculate_bill(units) that


to use control calculates the electricity bill based on the following
structures like if-else-if conditions: • First 100 units → Rs. 10 per unit • Next 100
conditions. units → Rs. 15 per unit • Above 200 units → Rs. 20 per unit
Call the function and display the total bill for 250 units.

Student Should be able 3. Create a class Student with the following attributes: •
to understand access name • roll_no • marks Include a method to calculate grade
specifiers, members based on marks. Create two objects and display their details
functions and member and grades.
elements, also able to
use object in classes.
Student Should be able 4. Write a Python program that: • Creates a dictionary
to use more advanced containing student names as keys and marks as values. •
programming construct Writes this dictionary data into a text file. • Reads the file
like dictionary and text and displays the contents.
files in python.

Student Should be able 5. Design a Tkinter GUI application that: • Takes user input
to make own interface (name and age). • Displays the entered information when a
using libraries. button is clicked. Explain the role of the mainloop() function
in Tkinter.

Page 47 of 102
Ser SLO Section Questions Answer
24. Students will be able to B [Link] a Python program to generate a dataset where y = 1. Python program for y = 2x + 1 (Line Chart & Box Plot)
generate a simple 2x + 1 and plot a line chart and a box plot. ✔ Explanation:
linear dataset using the We will:
formula y = 2x + 1 in • Create x values
Python. • Calculate y = 2x + 1
• Plot Line Chart
• Plot Box Plot
✔ Python Code:
import [Link] as plt

# Generate dataset
x = list(range(1, 11)) # x from 1 to 10
y = [2*i + 1 for i in x] # y = 2x + 1

# Line Chart
[Link]()
[Link](x, y)
[Link]("Line Chart of y = 2x + 1")
[Link]("X values")
[Link]("Y values")
[Link]()

# Box Plot
[Link]()
[Link](y)
[Link]("Box Plot of y = 2x + 1")
[Link]()

Students will be able to 2. Design a simple experiment to study the relationship ✔ Simple Experiment Design:
identify independent between study hours and test scores, and create a • Independent Variable: Study Hours
variable (study hours) scatter plot using Python or Excel to visualize the • Dependent Variable: Test Scores
and dependent relationship between the two variables. • Ask 10 students:
variable (test scores). o How many hours they studied?
o What score did they get?
✔ Sample Data:

Page 48 of 102
Ser SLO Section Questions Answer
Study Test
Hours Score
1 45
2 50
3 55
4 60
5 70
6 75
7 80
8 85
9 90
10 95
✔ Python Code (Scatter Plot):
import [Link] as plt

study_hours = [1,2,3,4,5,6,7,8,9,10]
test_scores = [45,50,55,60,70,75,80,85,90,95]

[Link](study_hours, test_scores)
[Link]("Study Hours vs Test Scores")
[Link]("Study Hours")
[Link]("Test Scores")
[Link]()
Observation: As study hours increase, test scores increase
(positive relationship).

Students will be able to 3. Create a line graph using pre-existing temperature ✔ Sample Temperature Data (°C):
explain the importance data of a city for 7 days to explain the importance of model Day Temperature
of model building in building in understanding real-world trends.
Mon 30
understanding real-
world trends. Tue 32
Wed 31
Thu 35
Page 49 of 102
Ser SLO Section Questions Answer
Fri 36
Sat 34
Sun 33
✔ Python Code:
import [Link] as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


temperature = [30, 32, 31, 35, 36, 34, 33]

[Link](days, temperature)
[Link]("7-Day Temperature Trend")
[Link]("Days")
[Link]("Temperature (°C)")
[Link]()
✔ Importance of Model Building:
• Helps understand trends
• Predict future temperature
• Supports planning (clothes, events, agriculture)

Students will be able to 4. Plot the linear relationship $y = 3x + 4$ using both a Line ✔ Python Code:
generate values using Chart and a Box Plot. import [Link] as plt
the linear equation y =
3x + 4. x = list(range(1, 11))
y = [3*i + 4 for i in x]

# Line Chart
[Link]()
[Link](x, y)
[Link]("Line Chart of y = 3x + 4")
[Link]("X values")
[Link]("Y values")
[Link]()

# Box Plot
[Link]()
Page 50 of 102
Ser SLO Section Questions Answer
[Link](y)
[Link]("Box Plot of y = 3x + 4")
[Link]()
This shows a linear increasing relationship.

Students will be able to 5. Formulate interview questions to investigate preferences ✔ Section A: Online vs Classroom Learning
analyze opinions for online learning vs. classroom learning and international 1. Which mode of learning do you prefer? (Online / Classroom)
regarding online study. 2. Why do you prefer this mode?
learning, classroom 3. Do you think online learning saves time?
learning, and 4. Do you feel more focused in classroom learning?
international study. 5. What challenges do you face in online learning?
6. What benefits do you see in classroom learning?
✔ Section B: International Study
7. Do you want to study abroad? (Yes / No)
8. Which country would you prefer and why?
9. What factors influence your decision? (Cost / Quality / Career
Opportunities)
10. Do you think international study improves career
opportunities?

25. Students will be B [Link] two application of block chain technology Two Applications of Block chain Technology in Pakistan
able to identify at applicable to Pakistan there are not presented in the Blockchain is a decentralized and secure digital ledger system.
least two real- text box .why they are needed and what improvement Below are two applications relevant to Pakistan:
world applications they can bring. 1. Land Record Management System
of blockchain ✔ Why Needed?
technology • In Pakistan, land disputes are common.
relevant to • Paper-based land records can be altered or forged.
Pakistan. • Corruption and fake ownership claims create legal problems.
✔ How Blockchain Can Help:
• Every land transaction is recorded permanently.
• Records cannot be changed or deleted.
• Ownership history becomes transparent.
✔ Improvements:
• Reduces land fraud.
• Increases trust in property transactions.
Page 51 of 102
Ser SLO Section Questions Answer
• Faster property transfer process.
• Decreases corruption in land departments.

2. Transparent Charity & Zakat Distribution System


✔ Why Needed?
• Pakistan collects large amounts of Zakat and charity.
• Sometimes funds are misused or not distributed properly.
• Donors do not always know where their money goes.
✔ How Blockchain Can Help:
• Every donation is recorded publicly.
• Funds can be tracked from donor to beneficiary.
• No one can secretly change the record.
✔ Improvements:
• Builds donor trust.
• Ensures fair distribution.
• Reduces financial mismanagement.
• Promotes transparency in NGOs and welfare programs.

Students will be [Link] five reason due to which data privacy can Five Reasons Data Privacy Issues Arise Among Stakeholders in
able to identify five arise among stakeholders in organization in Pakistan. Pakistan
key reasons that Data privacy concerns arise due to the following reasons:
cause data
privacy concerns 1. Weak Cybersecurity Systems
among Many organizations use outdated systems, making data vulnerable to
stakeholders. hacking.
2. Lack of Strong Data Protection Laws
Pakistan’s data protection regulations are still developing, so
enforcement is sometimes weak.
3. Unauthorized Access by Employees
Internal staff may misuse or leak sensitive information.
4. Poor Data Management Policies
Organizations may collect more data than necessary or store it
improperly.

Page 52 of 102
Ser SLO Section Questions Answer
5. Third-Party Data Sharing
Data is often shared with external vendors without clear consent from
stakeholders.
✔ Resulting Problems:
• Loss of customer trust
• Financial fraud
• Identity theft
• Legal consequences

[Link] the data anoymization and data Data Anonymization and Data Minimization
Students will be minimization with examples. Data Anonymization
able to explain the ✔ Definition:
importance of Data anonymization means removing personal identifiers so
these techniques individuals cannot be identified.
in protecting ✔ Example:
privacy. Before anonymization:
• Name: Ali Khan
• CNIC: 35201-1234567-8
• Phone: 03001234567
After anonymization:
• ID: User 001
• Age: 25
• City: Lahore
The person’s identity cannot be traced.
✔ Purpose:
• Protects privacy
• Used in research and surveys
• Prevents misuse of personal data

Data Minimization
✔ Definition:
Data minimization means collecting only the necessary data required
for a specific purpose.
✔ Example:
If a school admission form requires:
Page 53 of 102
Ser SLO Section Questions Answer
• Student Name
• Parent Contact Number
It should NOT ask for:
• Bank account details
• National ID of relatives
✔ Purpose:
• Reduces risk of data misuse
• Limits exposure in case of data breach
• Builds trust

[Link] the class into two group a stance on a data sharing Classroom Debate: Data Sharing vs Privacy Conflict
and privacy [Link] example on group could argue that Topic:
social media companies should be required to share user Should social media companies share user data with the government
data with the government to prevent terrorism ,while the to prevent terrorism?
other group could argue that this would be a violation of
privacy [Link] exercise will allow students to practice
arguing their points of view and develop their
communication and collabortation skill. Group A: Support Data Sharing (National Security First)
Arguments:
1. Prevents terrorist activities.
2. Helps law enforcement catch criminals.
3. Protects national security.
4. Can reduce cybercrime.
5. Saves innocent lives.
Conclusion:
Security of the nation is more important than individual privacy in
emergency situations.
Group B: Oppose Data Sharing (Privacy Rights First)
Arguments:
1. Violates individual privacy rights.
2. Can lead to government misuse of data.
3. Threatens freedom of speech.
4. Risk of surveillance abuse.
5. No guarantee that data won’t be misused.
Conclusion:
Page 54 of 102
Ser SLO Section Questions Answer
Privacy is a fundamental human right and must be protected.
Skills Developed Through This Activity:
• Critical thinking
• Communication skills
• Teamwork and collaboration
• Respect for different opinions
• Logical reasoning

Analyze the importance Q.5 Which principal should be adapted for data sharing and The Principle of Data Protection and Privacy by Design
of balancing data protection of privacy in Pakistan? This principle means that privacy and data protection should be built
sharing and privacy into systems from the beginning — not added later.
rights. Key Principles That Should Be Adopted in Pakistan
1. Lawful and Fair Data Collection
Organizations should collect data legally and with the knowledge of
individuals.
Example:
A bank must inform customers why their CNIC and contact details
are required.
2. Purpose Limitation
Data should only be used for the purpose for which it was collected.
Example:
If a school collects a student’s phone number for academic updates,
it should not use it for marketing.

3. Data Minimization
Only necessary data should be collected.
Example:
An online shopping website should not ask for unnecessary personal
details.

4. Consent and Transparency


Individuals must give clear consent before their data is shared.
Example:
Social media platforms should clearly explain how user data will be
used.

Page 55 of 102
Ser SLO Section Questions Answer
5. Security Safeguards
Organizations must protect data using strong cybersecurity systems.
Example:
Using encryption, strong passwords, and firewalls to prevent hacking.
6. Accountability
Organizations must be responsible for protecting the data they
collect.
Example:
If data is leaked, the organization should face penalties.

26. After completing this B 1. Identify and apply safe practices. Applying Safe Online Practices
topic, students will be You are working with diverse team to develop a new To ensure safety and security:
able to: educational website .Describe how you would use ✔ Use Secure Platforms
Identify safe online online collaborative tools and communication Use trusted tools like Google Docs, Microsoft Teams, or Zoom that
practices while working strategies to ensure all team members can contribute provide secure login systems.
in a digital environment. equally. ✔ Strong Passwords
All team members should use strong passwords and enable two-
factor authentication (2FA).
✔ Data Protection
Sensitive information (student data, website credentials) should not
be shared publicly. Access permissions should be limited.
✔ Respect Digital Etiquette
• No sharing private messages without permission.
• Respect different opinions.
• Avoid inappropriate language.
Using Online Collaborative Tools Effectively
✔ Shared Documents
Use shared documents so everyone can:
• Edit content
• Add ideas
• Comment on others’ work
This ensures equal participation.
✔ Task Management Tools
Use task boards (like Trello-style tools) to:
• Assign clear responsibilities

Page 56 of 102
Ser SLO Section Questions Answer
• Track deadlines
• Avoid confusion
✔ Cloud Storage
Store files in shared cloud folders so everyone has access to
updated versions.
Communication Strategies for Equal Contribution
✔ Clear Roles and Responsibilities
Assign roles such as:
• Content Writer
• Web Designer
• Researcher
• Editor
This avoids dominance by one person.
✔ Regular Meetings
Conduct weekly online meetings to:
• Discuss progress
• Solve problems
• Listen to everyone’s ideas
✔ Encourage Inclusive Participation
• Ask quiet members for their opinions.
• Rotate leadership roles.
• Use polls to collect feedback.
✔ Respect Cultural Diversity
Since the team is diverse:
• Be sensitive to language differences.
• Be respectful of cultural backgrounds.
• Maintain professional communication.

Ensuring Equal Contribution


To ensure fairness:
• Use collaborative editing tools where contribution history is
visible.
• Encourage feedback from all members.
• Set clear deadlines for everyone.
• Resolve conflicts through discussion, not arguments.

Page 57 of 102
Ser SLO Section Questions Answer

After studying this topic, [Link] cryptography ensure the safe transmission of data What is Cryptography?
students will be able to: ,detailing the difference between symmetric and asymmetric Cryptography is the process of converting readable data (plaintext)
Define cryptography encryption . into an unreadable form (ciphertext) to protect it from unauthorized
and explain its role in access. Only authorized users with a secret key can convert it back
secure communication. to readable form.
It ensures three main things:
1. Confidentiality – Only authorized persons can read the data.
2. Integrity – Data cannot be changed during transmission.
3. Authentication – Confirms the identity of sender and
receiver.
How Cryptography Protects Data during Transmission
When data is sent over the internet (for example: passwords, bank
details, messages), cryptography:
1. Converts the original data into encrypted form using an
encryption key.
2. Sends the encrypted data through the internet.
3. Even if hackers intercept the data, they cannot read it.
4. The receiver uses a key to decrypt the data and read the
original message.
Example:
Original Message (Plaintext):
Password123
Encrypted Message (Ciphertext):
Xy7#kP9@Lm2
Only the authorized receiver can convert it back.
Types of Encryption
There are two main types:
1. Symmetric Encryption
2. Asymmetric Encryption
1. Symmetric Encryption
✔ Definition:
Symmetric encryption uses one single key for both encryption and
decryption.

Page 58 of 102
Ser SLO Section Questions Answer
✔ How it works:
• Sender and receiver share the same secret key.
• The sender encrypts the data using the key.
• The receiver decrypts the data using the same key.
✔ Example:
Key = 5
Message = HELLO
Encrypted = MJQQT
Receiver uses same key (5) to decrypt.
✔ Advantages:
• Fast
• Efficient for large data
✔ Disadvantages:
• Key sharing is risky
• If key is stolen, data can be accessed
2. Asymmetric Encryption
✔ Definition:
Asymmetric encryption uses two keys:
• Public Key (used for encryption)
• Private Key (used for decryption)
✔ How it works:
• Public key is shared openly.
• Private key is kept secret.
• Sender encrypts data using public key.
• Only receiver can decrypt using private key.
✔ Example:
Public key encrypts message
Private key decrypts message
✔ Advantages:
• More secure
• No need to share private key
✔ Disadvantages:
• Slower than symmetric encryption

Page 59 of 102
Ser SLO Section Questions Answer
27. Students will be able to: B 1. Imagine you want to track plant growth overtime .How Questions From Official NBF Textbook 202
Plan and design a data would you design a system to collect data on this ?
collection system
Students will be able to [Link] a survey form to get collected data about the
perform: topic”How economic conditons of various countries are
• Advanced affected by the COVID -19 “?
searches to
locate
information
Design data collection
approach to gather
orginal data
Students will be able to [Link] are assigned to explore the reasons behind students' Questions from Official PBA Model Paper
to: preferences for online learning compared to in-person Premier PBA Computer Science HSSC
Design open-ended learning. What kind of questions would you ask in your
interview questions to interview to gather qualitative data on students' learning
collect qualitative data preferences (any four questions)?
Students will 2. You are conducting a survey to understand students'
understand that how to reading habits. Distribute the survey to 50 students in your
: class. Design a questionnaire having at least four
Design data collection appropriate questions to collect data about students' reading
approach to gather habits with closed ended questions.
borignal data gather
orginal data.
28. Student will be able to: B 1. (Section-A): Entrepreneur/MVP Scenario From the official PBA Model Paper:((Khurram Arsalan)
• Understand the You are an entrepreneur who wants to start an online T-
concept of MVP shirts store.
in an Your goal is to create an MVP (minimum viable product) to
entrepreneurial test your idea with potential customers.
context Answer the following:
• Identify essential • Identify the most essential feature for your online
features and store. (1 mark)
tools required to • Identify the tools/technologies you would use to build
build an online the Frontend and Backend. (1 mark)
product • After completing the MVP, gather feedback and
design three future improvements. (3 marks)
Page 60 of 102
Ser SLO Section Questions Answer

Students will be able to: 2. You are an Entrepreneur who wants to start an online
• Identify the core fast-food restaurant. Your goal is to create an MVP
features required (minimum viable product) to quickly test your idea with
to build an MVP potential customers.
Analyze user feedback Answer the following:
and plan improvements • Identify the most essential feature for the online
restaurant. (1 mark)
• Identify an appropriate tool and technology you will
use to create the Frontend and Backend. (1 mark)
• Once the MVP is complete, gather feedback from
potential users (friends, family etc.)
This question asks you to think like a product developer —
pick core features of your MVP, decide tech stack, and plan
future improvements based on feedback.
Students will be able to: 1. Lets suppose you are aiming to design an exciting From the official NBF TEXTBOOK :197
Create a basic model to skateboard ramp for your toy cars . What household items
test a design idea. could you gather to construct a rough and ready model for a
trial run?
Students will be able to: 1. (Alternate/OR part): Prototype Feedback From the same official PBA Model Paper:((Khurram Arsalan)
• Critically “Here is a prototype for an online bookstore.”
evaluate a Provide feedback to enhance its design and functionality:
prototypes • What is the strongest part of the design?
design and • What changes would you recommend to make the
usability prototype more engaging?
• Suggest • Are the labels easy to read and understand? Justify
meaningful your answer.
improvements • Would this chart help students learn about organizing
based on user and interpreting data?
experience • Is there any data you’d add to make the chart more
principles relatable for students?
Interpret and relate This prototype question assesses your ability to critique
data using charts and design and usability, not just write code.
visual impairments.

Page 61 of 102
Ser SLO Section Questions Answer
Students will be able to: 1. (Section-A, Part-b): Official Prototype Question (Composite PBA) pg 205
• Evaluate a Here is a prototype for an online bookstore. Provide
prototype design feedback on how to enhance its design and functionality.
and identify its • What do you think is the strongest part of the
strengths and design?
weakness • What changes would you recommend to make the
• Suggest design prototype more engaging?
and functional • Are the labels easy to read and understand?
improvements Justify your answer.
based on user • Would this chart help students learn about
needs. organizing and interpreting data?
Interpret and relate • Is there any data you think should be added to
data using charts and make the chart more relatable for students?
visual representations
Students will be able to: 1. Imagine you are ready to create an amazing new “bird From the OFFICIAL NBF TEXTBOOK: pg 205
• Identify suitable feeder” . What materials might you consider using to craft a
materials for rapid prototype?
rapid prototyping
Create a simple
prototype using easily
available resources
Students will be able to: 1 How can you develop a Minimum Viable Product(MVP)for From the ALL IN ONE KEYBOOK(pg 388):
• Understand the a sustainable packaging solution using real-world business
concept of MVP tools and techniques?
and its
importance in Q2
entrepreneurship i. Identify 2 core features of MVP.
. ii. Suggest tools/tech(Front+Backend).
• Identify essential iii. Suggest 2 improvements after feedback.
features required
to develop an Q3You are an Entreprenuer Who Wants to start an Online
MVP. Fast-Food Restaurant. Your Goal is to create an
Analyze user feedback MVP(Minimal Viable Product) to quickly test your idea with
and suggest potential customers
improvements for future [Link] the most essential feature for the online Fast-Food
development Restaurant.
Page 62 of 102
Ser SLO Section Questions Answer
[Link] an appropriate tool and technology you will use to
create the Frontend and Backend.
[Link] the MVP is complete, gather feedback from
potential users (friends,family etc.0 and plan future
improvements.
Design any three future improvements.
29. [SLO CS-11-A-01] B Q1. Simplify the following using Karnaugh map and also i) K-map:
Students will be able to construct the logic circuit for simplified diagram: B̅C̅ B̅C BC BC̅
understand and apply
logic gates in digital F=AB+ A̅B+AB̅C Ᾱ 1 1
systems, define and A 1 1
create truth tables
using Boolean Simplified Function F= A̅C+AB
operators like AND, ii) Simplified Logic circuit Diagram:
OR, NOT, NAND,
XOR) and logic
diagrams.

Q2. Simplify the following using Karnaugh map and also i) K-map:
construct the logic circuit for simplified diagram: B̅C̅ B̅C BC BC̅
Ᾱ 1 1
F = A̅B̅C+ A̅BC+ ABC̅+ ABC
A 1 1 1
Simplified Function F= A̅C+AB
ii) Simplified Logic circuit Diagram:

Q3. Consider the following logic statement: i) Logic circuit Diagram:


X = ((A OR B) AND (NOT (B XOR C)) AND C)
Draw a logic circuit to represent the given logic statement.
Page 63 of 102
Ser SLO Section Questions Answer


Q4. a) A security system allows access only when: a) Boolean Expression:
• Keycard is valid (A = 1) i) Access = A .B. C̅
• Password is correct (B = 1) ii) Required Logic Gates:
• Alarm system is inactive (C = 0) • NOT Gate (Inverter): To flip the Alarm signal (C)
i) Write the Boolean expression from 0 to 1.
ii) Name the required logic gates • AND Gate: To combine the signals.
b) Design a logic circuit that produces output 1 only b)
when exactly one input is 1. i) For two inputs (A and B), this is the XOR Gate (Exclusive
i) Name the gate OR).
ii) Write its Boolean expression ii) Y = A ⊕ B
iii) Draw its logic symbol Alternatively, in expanded form: Y = A̅B + AB̅
iii) Logic Symbol

4.
[Link] truth table for the following:

F = XYZ + X̅Y + YZ̅ X Y Z X̅ Z̅ XYZ X̅Y YZ̅ F (Output)


0 0 0 1 1 0 0 0 0
0 0 1 1 0 0 0 0 0
0 1 0 1 1 0 1 1 1
0 1 1 1 0 0 1 0 1
1 0 0 0 1 0 0 0 0
Page 64 of 102
Ser SLO Section Questions Answer
1 0 1 0 0 0 0 0 0 Truth
1 1 0 0 1 0 0 1 1 Table:
1 1 1 0 0 1 0 0 1
Q6. An automatic door opens (D = 1) when: 1. Boolean Expression & Truth Table
• The motion sensor detects someone (M = 1) D= (M + R). S̅
• OR the remote switch is ON (R = 1) M) R S (M+R) S̅ D (Door)
• AND the safety lock is OFF (S = 0) 0 0 0 0 1 0
1. Write the Boolean expression for door control. 0 0 1 0 0 0
2. Draw the truth table for all combinations of M, R and S. 0 1 0 1 1 1
Draw the logic diagram using AND, OR, and NOT gates. 0 1 1 1 0 0
1 0 0 1 1 1
1 0 1 1 0 0
1 1 0 1 1 1
1 1 1 1 0 0
30. [SLO CS-11-B-01] B Q1. Write a pseudocode and draw a flowchart to show Start
Plan, develop, how a computer system checks whether a given number is Input number
systematically test, and even or odd. If number MOD 2 = 0 then
refine computational Print "Even Number"
artifacts for problem- Else
solving such as pseudo Print "Odd Number"
code, etc. End If
1. End
Q2. A school wants to develop a system that determines a) Pseudocode
whether a student is eligible for a scholarship. Start
The criteria are: Input total_marks
• Total marks ≥ 400 Input attendance_percentage
• Attendance ≥ 75%
a) Write a pseudocode to check eligibility based on the If total_marks ≥ 400 AND attendance_percentage ≥ 75 then
above conditions. Print "Eligible for Scholarship"
b) Suggest two test cases (inputs and expected outputs) to Else
verify the correctness of your pseudocode. Print "Not Eligible for Scholarship"
End If
End
b) Test Case 1: A student with 420 marks and 80% attendance is
eligible for scholarship.
Page 65 of 102
Ser SLO Section Questions Answer

Test Case 2: A student with 380 marks and 85% attendance is not eligible for
scholarship.
[Link] following algorithm gives incorrect output: a) Logical error:
Start
Read marks • The algorithm prints "Fail" when marks are greater than 50.
If marks > 50
Print "Fail" • This is logically incorrect because normally a student passes if
Else marks > 50 and fails if marks ≤ 50.
Print "Pass"
End If Error: The condition is reversed.
End
a) Identify the logical error in the algorithm. b) Correct Algorithm
b) Rewrite the correct algorithm. Start
Read marks
If marks ≥ 50 then
Print "Pass"
Else
Print "Fail"
End If
End
Q4. Study the flowchart carefully and complete the trace TRACE TABLE:
table for the given inputs:

INPUT OUTPUT
X S
48 2
9170 4
- 800 1

Page 66 of 102
Ser SLO Section Questions Answer

Q5. A shop owner wants to calculate the total price of a) Start


items. If quantity is more than 10, price is reduced by Rs. 50. Input quantity
(3+3) Input price_per_item
a) Write an algorithm for the above problem. total_price = quantity * price_per_item
b) Create a trace table for quantity = 12 and price_per_item If quantity > 10 then
= Rs. 500. total_price = total_price - 50
End If
Print "Total Price =", total_price
End
b)
Ste quantit price_per_ite total_pric Conditio Updated
p y m e n total_pric
(quantity e
> 10)
1 12 500 – – –
2 12 500 12 × 500 12 > 10 6000 - 50
= 6000 → True = 5950
3 – – 5950 – –

Final Output: Total Price = 5950

Page 67 of 102
Ser SLO Section Questions Answer
Q6. Write a pseudocode to find and display a factorial of any Start
number. Input n
factorial = 1
For i = 1 to n
factorial = factorial * I
End For
Print "Factorial of", n, "is", factorial
End
31. [SLO CS-11-B-02] B Q1. Write an algorithm for linear search to find the number Start
Apply common search, 42 in a list [12, 25, 42, 51, 66]. list = [12, 25, 42, 51, 66]
and sort algorithms target = 42
found = False
For i = 1 to length of list
If list[i] = target then
Print "Number found at position", i
found = True
Exit For
End If
End For
If found = False then
Print "Number not found"
End If
End
Q2. Write a binary search algorithm to find the number 15 in List: [24, 13, 2, 51, 6, 15, 6]
the given list:
[24, 13, 2, 51, 6, 15, 6]. Step 1: Sort the list first (Binary Search requires sorted list)
Sorted list: [2, 6, 6, 13, 15, 24, 51]

Binary Search Algorithm:

Start
list = [2, 6, 6, 13, 15, 24, 51]
target = 15
low = 1
high = length of list
found = False
Page 68 of 102
Ser SLO Section Questions Answer
While low ≤ high
mid = (low + high) / 2
If list[mid] = target then
Print "Number found at position", mid
found = True
Exit While
Else If list[mid] < target then
low = mid + 1
Else
high = mid - 1
End If
End While
If found = False then
Print "Number not found"
End
Q3. Given the list: a) Sorting Algorithm (Ascending Order)
[18, 5, 12, 9, 3] We can use any sorting algorithm (e.g., Bubble Sort):
a) First, apply and then write a sorting algorithm to arrange Steps:
the list in ascending order. 1. [18, 5, 12, 9, 3] → Pass 1 → [5, 12, 9, 3, 18]
b) After sorting, apply Binary Search to find the element 12. 2. Pass 2 → [5, 9, 3, 12, 18]
3. Pass 3 → [5, 3, 9, 12, 18]
4. Pass 4 → [3, 5, 9, 12, 18]
Sorted list: [3, 5, 9, 12, 18]
Algorithm for Sorting (Bubble Sort example):
Start
list = [18, 5, 12, 9, 3]
n = length of list
For i = 1 to n-1
For j = 1 to n-i
If list[j] > list[j+1] then
Swap list[j] and list[j+1]
End If
End For
End For
Print "Sorted list =", list
End
Page 69 of 102
Ser SLO Section Questions Answer
b) Binary Search for 12
Sorted list: [3, 5, 9, 12, 18]
Binary Search Steps:
• low = 1, high = 5 → mid = 3 → list[3] = 9 < 12 → low = 4
• low = 4, high = 5 → mid = 4 → list[4] = 12 → Found
Answer: Number found at position 4

Q4. Given the list: [22, 14, 9, 30, 18] a) Apply Insertion Sort
a) Apply Insertion Sort to arrange the list in ascending
order. Pass 1: [22, 14, 9, 30, 18] → 14 inserted before 22 → [14, 22, 9, 30,
b) Write an algorithm for insertion sort. 18]
Pass 2: 9 inserted before 14 → [9, 14, 22, 30, 18]
Pass 3: 30 already in correct place → [9, 14, 22, 30, 18]
Pass 4: 18 inserted between 14 and 22 → [9, 14, 18, 22, 30]

Final sorted list: [9, 14, 18, 22, 30]

b) Algorithm for Insertion Sort


Start
list = [22, 14, 9, 30, 18]
n = length of list
For i = 2 to n
key = list[i]
j=i-1
While j > 0 AND list[j] > key
list[j+1] = list[j]
j=j-1
End While
list[j+1] = key
End For
Print "Sorted list =", list
End
Q5. A shop owner wants to arrange product prices in a) Apply Bubble Sort
descending order.
[450, 200, 700, 300] Pass 1: Compare and swap → [450, 700, 200, 300] → [700, 450,
a) Apply Bubble Sort and show each pass clearly. 200, 300] → [700, 450, 300, 200]
Page 70 of 102
Ser SLO Section Questions Answer
b) Write the final sorted list. Pass 2: [700, 450, 300, 200] → No swaps needed

Pass 3: [700, 450, 300, 200] → Already sorted

b) Final Sorted List (Descending):

[700, 450, 300, 200]


32. [SLO CS-11-C-01] A Q1. A company wants to automate salary calculation. name = input("Enter employee name: ")
Students should Write a Python program that: salary = float(input("Enter basic salary: "))
understand the • Takes employee name and basic salary as input
importance of computer bonus = salary * 0.10
programming and • Calculates 10% bonus tax = salary * 0.05
applications • Calculates 5% tax deduction final_salary = salary + bonus - tax
• Displays final salary
print("Employee Name:", name)
This program shows how programming helps automate print("Bonus:", bonus)
payroll systems. print("Tax Deduction:", tax)
print("Final Salary:", final_salary)
Q2. Write a Python program that: m1 = int(input("Enter marks for Subject 1: "))
• Takes marks of three subjects m2 = int(input("Enter marks for Subject 2: "))
• Calculates total and average m3 = int(input("Enter marks for Subject 3: "))
• Assigns grade (A, B, C, Fail)
• Displays the result total = m1 + m2 + m3
average = total / 3

if average >= 80:


grade = "A"
elif average >= 60:
grade = "B"
elif average >= 40:
grade = "C"
else:
grade = "Fail"
print("Total:", total)
print("Average:", average)
print("Grade:", grade)
Page 71 of 102
Ser SLO Section Questions Answer
Q3. Write a Python program that: balance = 5000
• Stores initial balance print("1. Deposit")
• Allows user to deposit or withdraw money print("2. Withdraw")

• Displays updated balance choice = int(input("Enter your choice: "))


This shows how programming is used in banking systems.
if choice == 1:
amount = float(input("Enter deposit amount: "))
balance += amount
elif choice == 2:
amount = float(input("Enter withdrawal amount: "))
if amount <= balance:
balance -= amount
else:
print("Insufficient balance")
else:
print("Invalid choice")

print("Current Balance:", balance)


Q4. Write a Python program that: p1 = float(input("Enter price of product 1: "))
• Takes prices of three products p2 = float(input("Enter price of product 2: "))
• Calculates total cost p3 = float(input("Enter price of product 3: "))
• Applies 10% discount if total exceeds 5000
• Displays final bill total = p1 + p2 + p3
This demonstrates the application of programming in online
shopping systems. if total > 5000:
discount = total * 0.10
else:
discount = 0

final_bill = total - discount

print("Total:", total)
print("Discount:", discount)
print("Final Bill:", final_bill)

Page 72 of 102
Ser SLO Section Questions Answer
Q5. Write a Python program that converts temperature from celsius = float(input("Enter temperature in Celsius: "))
Celsius to Fahrenheit. fahrenheit = (celsius * 9/5) + 32
This shows programming application in scientific
calculations. print("Temperature in Fahrenheit:", fahrenheit)
33. [SLO CS-11-C-02] A Q1. Write a Python program to swap two numbers. a = int(input("Enter first number: "))
Students should be able to write and b = int(input("Enter second number: "))
execute simple programs in Python. a, b = b, a
print("After swapping:")
print("First number:", a)
print("Second number:", b)
Q2. Write a Python program to convert total minutes into total_minutes = int(input("Enter total minutes: "))
hours and remaining minutes.
hours = total_minutes // 60
minutes = total_minutes % 60

print("Hours:", hours)
print("Remaining Minutes:", minutes)
Q3. An online store charges 5% tax on the total purchase amount = float(input("Enter purchase amount: "))
amount. Write a Python program that takes purchase tax = amount * 0.05
amount as input and calculates the final amount including final_amount = amount + tax
tax.
print("Tax amount:", tax)
print("Final amount including tax:", final_amount)
Q4. Create a simple health tool that calculates Body Mass weight = float(input("Enter your weight in kg: "))
Index (BMI). The formula is: BMI =
𝑤𝑒𝑖𝑔ℎ𝑡 height = float(input("Enter your height in meters (e.g., 1.75): "))
2
ℎ𝑒𝑖𝑔ℎ𝑡
Weight is in kg, height is in meters. bmi = weight / (height ** 2)

print(f"\nYour calculated BMI is: {bmi:.1f}")

if bmi < 18.5:


print("Category: Underweight")
elif 18.5 <= bmi < 25:
print("Category: Normal weight")
else:
print("Category: Overweight")
Page 73 of 102
Ser SLO Section Questions Answer
Q5. Write a Python program for a number guessing game correct_number = 7
where the correct number is 7.
The program should repeatedly ask the user to guess the while True:
number. If the guess is greater than 7, display “Too High”; if guess = int(input("Guess the number: "))
it is less than 7, display “Too Low”.
The program should continue until the correct number is if guess > correct_number:
guessed, then display a success message and stop. print("Too High")
elif guess < correct_number:
print("Too Low")
else:
print("Correct Guess!")
break
Q6. Create a Python program for a cafe that sells Burgers total = 0
(Rs. 500), Pizzas (Rs. 1000), and Sandwiches (Rs. 300).
The program must allow a user to enter their choice while True:
repeatedly and keep track of a running total. print("1. Burger (500)")
The loop should only end when the user enters 0. Finally, print("2. Pizza (1000)")
display the total bill amount. print("3. Sandwich (300)")
print("0. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
total += 500
elif choice == 2:
total += 1000
elif choice == 3:
total += 300
elif choice == 0:
break
else:
print("Invalid choice")
print("Total bill is:", total)

Page 74 of 102
Ser SLO Section Questions Answer
34. [SLO CS-11-C-03] A Q1. Using Python Turtle, draw an equilateral triangle with import turtle
Students should be able to draw shapes
sides of 150 units. [Link](150)
using Turtle Graphics functions in Python [Link](120)
[Link](150)
[Link](120)
[Link](150)
[Link](120)
Q2. Write a Python program using Turtle Graphics to draw import turtle
a square with each side 100 units using any loop. t = [Link]() # Create a new turtle named 't'

for i in range(4):
[Link](100)
[Link](90)

[Link]()
Q3. Draw a house shape using Turtle Graphics. The house import turtle
should have a square base of 100 units and a triangle roof t = [Link]() # Create a new turtle named 't'
on top. # Draw square base
for _ in range(4):
[Link](100)
[Link](90)

# Draw triangle roof


[Link](45)
[Link](70) # approx. length for diagonal
[Link](90)
[Link](70)
[Link]()

[Link]() # Finish the turtle program and keep the window open
Q4. Draw a circle inside a square using Turtle. The square import turtle
should have a side of 200 units and the circle should fit t = [Link]()
exactly inside the square. # Draw square
for i in range(4):
[Link](200)
[Link](90)
Page 75 of 102
Ser SLO Section Questions Answer
# Move turtle to center
[Link]()
[Link](100, -100) # center of square
[Link]()

# Draw circle with radius 100


[Link](100)
Q5. Develop a Python program to draw a star using Turtle import turtle
Graphics. t = [Link]()

for x in range(5):
[Link](100)
[Link](144) # angle for star points

[Link]()
35. [SLO CS-11-C-04] A Q1. Write a program that asks the user for the radius and import math
Students should be height of a cylinder. Calculate and display its volume. radius = float(input("Enter the radius of the cylinder:"))
able to understand the Formula: V = π r2h height = float(input("Enter the height of the cylinder:"))
need for libraries and
learn the use of some # Using [Link] and [Link] for precision
simple libraries in volume = [Link] * [Link](radius, 2) * height
Python.
print(f"The volume of the cylinder is: {round(volume, 2)} cubic units.")
Q2. Write a program that takes two integers from the user import math
and calculates their Greatest Common Divisor (GCD) using num1 = int(input("Enter first number: "))
a built-in library function. num2 = int(input("Enter second number: "))
result = [Link](num1, num2) # [Link] is much faster than writing
a manual loop
print(f"The GCD of {num1} and {num2} is: {result}")
Q3. Create a simulation where a user rolls a six-sided die. import random
The program should output a random number between 1 print("Rolling the die...")
and 6 using random library. # randint includes both the start and end values

roll = [Link](1, 6)
print(f"You rolled a: {roll}")

Page 76 of 102
Ser SLO Section Questions Answer
Q4. Write a program that prints the current date and time in import datetime
a readable format (e.g., YYYY-MM-DD HH:MM:SS). # Get current date and time
now = [Link]()

# Format using strftime (String Format Time)


formatted_date = [Link]("%Y-%m-%d %H:%M:%S")

print(f"Current Date and Time: {formatted_date}")


Q5. Create a GUI where a user can type their name into an import tkinter as tk
input box. When they click a "Submit" button, the program
should print "Hello [Name]" in the console. def greet():
name = [Link]() # .get() retrieves the text from the entry box
print(f"Hello {name}")

root = [Link]()
entry = [Link](root)
[Link](pady=10)

btn = [Link](root, text="Submit", command=greet)


[Link]()
[Link]()
Q6. Create a GUI with two entry boxes for numbers and a import tkinter as tk
"Calculate" button. When clicked, display the sum of the two def add():
numbers in a third Label. num1 = int([Link]()) # Get numbers from entries
num2 = int([Link]())
total = num1 + num2 # Calculate
[Link](text=total) # Update the label

root = [Link]()
# Input boxes
e1 = [Link](root)
[Link]()
e2 = [Link](root)
[Link]()

# The Button
Page 77 of 102
Ser SLO Section Questions Answer
btn = [Link](root, text="Add", command=add)
[Link]()

# The Output Label


result = [Link](root, text="0")
[Link]()
[Link]()
36. [SLO CS-11-C-05] A Q1. Write a Python program to calculate the sum of all n = int(input("Enter a positive integer: "))
Students should be able to translate natural
simple numbers from 1 to n, where n is entered by the user. total = 0
algorithms that use sequence and
repetition in Python. for i in range(1, n + 1):
total += i

print(f"The sum of the first {n} numbers is: {total}")


Q2. Write a program to input a number and print its table. num = int(input("Enter the number for the table: "))

print(f"Multiplication Table for {num}:")


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Q3. Write a Python program to calculate the factorial of a num = int(input("Enter a number: "))
number n entered by the user. The program must handle the factorial = 1
special case where 0! = 1 and include a check to prevent
calculations for negative integers. if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}")
Q4. Write a Python program that continuously accepts total = 0
numbers from a user and calculates their sum. The program
should stop (terminate) when the user enters 0 and then while True:
display the final total. num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
Page 78 of 102
Ser SLO Section Questions Answer
total += num

print(f"The total sum of entered numbers is: {total}")


Q 5. A system allows a user 3 attempts to enter the correct secret_pass = "python123"
password. If they get it right, it prints "Access Granted". If attempts = 3
they fail 3 times, it prints "Account Locked."
while attempts > 0:
guess = input(f"Enter password ({attempts} attempts left): ")
if guess == secret_pass:
print("Access Granted!")
break
else:
attempts -= 1
print("Wrong password.")

if attempts == 0:
print("Account Locked.")
Q6. A fitness app needs a "Water Intake Tracker." The goal a) total_water = 0
is to drink 2000ml of water a day. The program should ask while total_water < 2000:
the user to enter the amount of water (in ml) they just drank. added = int(input("Enter ml drunk: "))
It should keep adding to a total until the goal of 2000ml is total_water += added
reached. Once reached, it should congratulate the user. print(f"Total so far: {total_water}ml")
b) Write a Python program that implements the scenario
above and print the current total after every glass of print("Goal reached! Stay hydrated!")
water added. b) Missing Colon: while counter < 5 needs a :.
c) A programmer tried to write a similar program to count
how many glasses of water were drunk, but the code Type Error: input must be converted to int
has three errors. Identify and fix them.
counter = 0 Concatenation Error: print("... " + counter + " ...") fails because
while counter < 5 counter is an integer. It must be str(counter) or use a comma or f-
amount = input("Enter ml: ") string.
counter = counter + 1
print("You drank " + counter + " glasses!") Corrected Code:
d) Modify your program in Part (a) so that if a user enters a counter = 0
negative number (like -50), the program prints "Invalid while counter < 5:
amount" and does not add it to the total. amount = input("Enter ml: ")
Page 79 of 102
Ser SLO Section Questions Answer
What will be the output of this specific snippet? counter = counter + 1
print(f"You drank {counter} glasses!")

c)
# Adding an if-statement inside the loop
if added > 0:
total_water += added
else:
print("Invalid amount")
d) 200
400
600
37. [SLO CS-11-C-06] A Q1. Write a program to calculate both the area and def calc_area(r):
Students should be circumference of a circle given its radius using functions. return 3.15 * r**2
able to decompose a
problem into sub- def calc_circum(r):
problems and return 2 * 3.15 * r
implement those sub-
problems using radius = float(input("Enter radius: "))
functions in Python print(f"Area: {calc_area(radius):.2f}")
• print(f"Circumference: {calc_circum(radius):.2f}")
Q2. Given a list of numbers, find the sum of only the even def is_even(n):
numbers. Write a program using functions return n % 2 == 0

def sum_evens(my_list):
total = 0
for num in my_list:
if is_even(num):
total += num
return total

numbers = [1, 2, 3, 4, 5, 6]
print("Sum of evens:", sum_evens(numbers))
Q3. A smart home system checks two things: is it "Dark" def check_sensors(dark, motion):
outside and is there "Motion" detected? The light only turns return dark == "yes" and motion == "yes"
on if both are True.
Page 80 of 102
Ser SLO Section Questions Answer
def light_system():
# Get user input and convert to lowercase to prevent errors if user
types 'YES'
is_dark = input("Is it dark? (yes/no): ").lower()
is_motion = input("Is motion detected? (yes/no): ").lower()

if check_sensors(is_dark, is_motion):
print("ACTION: Light ON")
else:
print("ACTION: Light OFF")
# Calling the main function to start the program
light_system()
Q4. At the end of a game, the program needs to check if the def check_record(current, record):
current score is higher than the previous high score. Write a if current > record:
Python program that uses a function to check if a new score print("New High Score!")
is higher than the current high score. Return and print the return current
updated high score. return record

# Main Program
old_high = 500
user_score = int(input("Enter score: "))

# Call function and update variable


old_high = check_record(user_score, old_high)

print("Current High Score:", old_high)


Q5. Write a program using function that returns True if a def is_prime(n):
number is prime and False otherwise. The program should if n < 2:
asks the user for a range (start and end) of numbers and return False
prints all prime numbers in a given range. for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Main Program
low = int(input("Enter start of range: "))
Page 81 of 102
Ser SLO Section Questions Answer
high = int(input("Enter end of range: "))

print(f "Primes between {low} and {high}:")


for num in range(low, high + 1):
if is_prime(num):
print(num, end=" ")
38. [SLO CS-11-C-07] A Q1. Identify all errors in the program. Errors:
Students will determine Correct the program so that it executes properly.
ways of debugging their total = 0 Missing colon : in for loop
code in Python for i in range(5)
num = input("Enter a number: ") input() returns string; must convert to int
total = total + num
print("Total is", total) Corrected Program:

total = 0
for i in range(5):
num = int(input("Enter a number: "))
total = total + num
print("Total is", total)
Q2. The following program is meant to print even numbers Logical Error: Program prints odd numbers
from 1 to 10, but it prints something else. (i % 2 == 1) instead of even numbers.

for i in range(1, 10): Corrected Program:


if i % 2 == 1:
print(i) for i in range(1, 11):
Identify the logical error and correct the program so it prints if i % 2 == 0:
only even numbers print(i)
Q3. A student wants to take age as input and print it, but the try:
program crashes if a non-numeric value is entered. age = int(input("Enter your age: "))
age = int(input("Enter your age: ")) print("Your age is", age)
print("Your age is", age) except ValueError:
Modify the program to handle invalid input using try-except. print("Invalid input! Please enter a number.")
Q4. The following code is intended to calculate the average a) The error is a ZeroDivisionError. This occurs because
of a list of numbers, but it’s producing the wrong result or len(numbers) is 0 when the list is empty, and division by zero is
crashing. undefined.
def get_average(numbers):
Page 82 of 102
Ser SLO Section Questions Answer
total = 0 b) def get_average(numbers):
for num in numbers: if not numbers: # Guard clause
total += num return 0
return total / len(numbers) total = 0
for num in numbers:
my_list = [ ] total += num
print(get_average(my_list)) return total / len(numbers)
a) Identify the specific error that occurs when my_list is
empty. By placing print(f"Current total: {total}") inside the for loop we can see the runn
b) Rewrite the function to include a guard clause (an if update in real-time.
statement) that prevents a Zero Division Error.
c) Explain how you would use a print() statement to verify the
value of total during each iteration of the loop.
Q5. This code is meant to print every item in a list of fruits. a) It crashes when i is 3. . The valid indices are 0, 1, 2
Use range(len(fruits)) or range(0, 3).
fruits = ["Apple", "Banana", "Cherry"]
for i in range(1, 4):
print(fruits[i])

a) This code will produce an IndexError. On which specific


value of i does it crash?
. Rewrite the range() function so it prints all three fruits
correctly.
39. . [SLO CS-11-D-01] B Q1. Use Python to create two lists: import [Link] as plt
Students will be able to x = [2, 4, 6, 8] and y = [5, 10, 15, 20],
relate the role and then draw a scatter plot and bar chart. x = [2, 4, 6, 8]
importance of model y = [5, 10, 15, 20]
building with their real-
world applications # Scatter plot
[Link](x, y)
[SLO CS-11-D-02] [Link]("X values")
Students will understand [Link]("Y values")
and explain [Link]("Scatter Plot of X and Y")
experimental design in [Link]()
data science
# Bar chart
Page 83 of 102
Ser SLO Section Questions Answer
[SLO CS-11-D-03] [Link](x, y)
Students will analyze [Link]("X values")
pre-existing data sets [Link]("Y values")
to create summary [Link]("Bar Chart of X and Y")
statistics and data vi) [Link]()
visuals (such as bar Q2. Write a Python program to generate a dataset import [Link] as plt
charts, pie charts, line representing the square of numbers from 1 to 10. Plot:
graphs etc. a) a bar chart of x versus y x = list(range(1, 11))
b) a box plot of the output values y = [i*i for i in x]

[Link](x, y)
[Link]("X")
[Link]("Y")
[Link]("Bar Chart of Squares")
[Link]()

[Link](y)
[Link]("Box Plot of Squares")
[Link]("Y")
[Link]()
Q3. Write a Python program to generate a dataset import [Link] as plt
representing students’ marks in a test (any 10 values). Draw:
a) a bar chart of student number versus marks students = list(range(1, 11))
b) a box plot of the marks marks = [65, 70, 72, 68, 80, 85, 90, 75, 78, 82]

[Link](students, marks)
[Link]("Student Number")
[Link]("Marks")
[Link]("Students Marks")
[Link]()

[Link](marks)
[Link]("Box Plot of Marks")
[Link]("Marks")
[Link]()

Page 84 of 102
Ser SLO Section Questions Answer
Q4. Write a Python program to generate values of y using import [Link] as plt
the formula
y = x3 for values of x from 1 to 8. x = list(range(1, 9))
Then draw a line chart of x and y. y = [i**3 for i in x]

[Link](x, y)
[Link]("X")
[Link]("Y")
[Link]("Line Chart of y = x³")
[Link]()
Q5. Write a Python program to generate a dataset showing import [Link] as plt
monthly rainfall (in mm) for 6 months.
Plot: months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
a) a line graph of months versus rainfall rainfall = [20, 35, 50, 40, 60, 55]
b) a box plot of rainfall data
[Link](months, rainfall)
[Link]("Months")
[Link]("Rainfall (mm)")
[Link]("Monthly Rainfall")
[Link]()

[Link](rainfall)
[Link]("Box Plot of Rainfall")
[Link]("Rainfall (mm)")
[Link]()
40. [SLO CS-11-G-01] B Q1. Design 4 survey questions about students’ study habits a) 4 Closed-ended Survey Questions:
Perform advanced (closed-ended) and 3 interview questions about their 1. How many hours do you study per day?
searches to locate preferred learning methods (open-ended). o ☐ Less than 1 hour
information and/or o ☐ 1–2 hours
design a data-collection o ☐ 3–4 hours
approach to gather
o ☐ More than 4 hours
original data (e.g.
qualitative interviews, 2. Which time of day do you prefer for studying?
surveys, prototypes, o ☐ Morning
simulations) o ☐ Afternoon
o ☐ Evening
Page 85 of 102
Ser SLO Section Questions Answer
o ☐ Night
3. How often do you revise your lessons?
o ☐ Daily
o ☐ Weekly
o ☐ Monthly
o ☐ Rarely
4. Do you study alone or with friends?
o ☐ Alone
o ☐ With friends
o ☐ Both
b) 3 Open-ended Interview Questions about Learning Methods:
1. Which method of learning helps you understand topics better
(e.g., reading, videos, group study)? Why?
2. Can you describe any specific technique that makes studying
easier for you?
How do you prefer teachers to explain new topics in class?
Q2. Your school wants to collect data about students’ a) 3 Survey Questions:
internet usage habits. 1. How many hours per day do you use the internet?
a) Design three survey questions that can be used to collect o ☐ Less than 1 hour
this data. o ☐ 1–2 hours
b) Identify the type of data (qualitative or quantitative) for o ☐ 3–4 hours
each question.
o ☐ More than 4 hours
2. For which purpose do you mostly use the internet?
o ☐ Education/Research
o ☐ Social Media
o ☐ Entertainment
o ☐ Gaming
3. Which device do you use most to access the internet?
o ☐ Smartphone
o ☐ Laptop/PC
o ☐ Tablet
o ☐ Others
b) Type of Data:
Page 86 of 102
Ser SLO Section Questions Answer

1. Hours per day: Quantitative (numerical ranges)


2. Purpose of internet usage: Qualitative (categorical)
3. Device used: Qualitative (categorical)
Q3. A computer teacher wants to improve the computer lab a) Data-collection Method:
experience for students.
a) Select one data-collection method Observation – to directly see how students use the lab, their
b) Describe one observation checklist item that can be used behavior, and difficulties.
to collect relevant data.
c) Develop any two questions (for interview or survey). b) Observation Checklist Item:

“Student can access and operate software independently without


asking for help.”

c) Two Questions (Survey or Interview):

• What difficulties do you face while using the computer lab?

Which software or resources would you like to have in the lab to


improve your learning?
Q4. You want to ask 500 computer experts which 1.
programming language they like most. You only have one • Time: Talking to one person takes at least 30 minutes. If you
week to finish your report. talk to 500 people, it would take 250 hours! That is impossible
1. Why is it a bad idea to try and talk (interview) to all 500 to finish in just one week.
people one-by-one? • Difficulty: It is very hard to organize 500 meetings and write
2. Instead of talking to them, what is a faster way to get down everything they say in such a short time.
their answers using a computer? 2.
If you talk to them, you get long stories. If you use your new • The Online Survey (or Questionnaire): You should send
faster method, you get numbers and charts. What is the them a link (like a Google Form). They can all answer at the
name for this "number-based" data? same time, and the computer collects the results for you
automatically.
3. Qualitative vs. Quantitative (Stories vs. Numbers)
• Qualitative (Interviews): This is "story data." You get long,
detailed opinions about why they like a language.
• Quantitative (Surveys): This is "number data." Instead of
stories, you get facts like: "80% of experts like Python." This
Page 87 of 102
Ser SLO Section Questions Answer
is much faster to put into a chart or graph.

Q5. After introducing online classes, the school wants • Interview Questions (Open-ended)
feedback from students. 1. What do you like most about online classes, and why?
2. What challenges do you face while attending online classes?
• Write two interview questions to gather students’ opinions
about online learning. • Survey Questions (Closed-ended)
Write two closed-ended survey questions to measure 1. How satisfied are you with the quality of online classes?
students’ satisfaction level. o Very satisfied
o Satisfied
o Neutral
o Dissatisfied
o Very dissatisfied
2. Do you feel online classes help you understand your lessons
better?
o Yes
o No

Q6. A student makes a Paper Prototype (a drawing on b) No: "It looks nice" is an opinion, not functional data. It doesn't tell
paper) of a new school website. He shows it to a friend. The us if the website actually works.
friend says, "It looks nice," and walks away.
c. The Task: "Please try to find the 'Class 11 Date Sheet' on this
a) Did the student collect good "Data" from this test? Why or paper and point to where you would click." (This collects Usability
why not? Data).
Give the student one specific task to tell his friend to do
(e.g., "Find the exam schedule") to get better data.

Page 88 of 102
Ser SLO Section Questions Answer
41. [SLO EN-11-H-01] A i) Best Working Part
Students will create, The Shopping Cart sidebar is best because it clearly shows the total
test, and iterate a price and allows for a quick checkout.
prototype for a
business idea ii) Suggested Improvements
Use real-life photos instead of drawings and add a bold discount
banner to the hero section.

iii) Clarity of Labels


The labels are very clear because they use standard terms like "Add
to Cart" and "Search" that everyone understands.
Q1. iv) Browsing and Selection
Yes, it is easy because users can find items using either the top
Here is a prototype for an online clothing store. Provide categories or the side filters.
feedback on how to enhance its design and functionality.
i) Which part of the prototype do you think works the v) Additional Information
best? ▪ Add customer star ratings and a "Size Guide" to help users feel
ii) Suggest at least two improvements or features that more confident about their purchase.
could make the prototype more visually appealing and
engaging for users.
iii) Evaluate the clarity of the labels and text. Are they
easy for users to understand? Support your answer with
examples.
iv) Do you think this prototype allows customers to
browse and select clothes easily? Give reason.
v) What additional information, features, or data could be
added to make the online store more useful and relatable for
users?

Page 89 of 102
Ser SLO Section Questions Answer
i) Strongest Part of Design
The "Today’s Workout" banner is the strongest part because it
highlights the main action with a clear "Start" button.

ii) Recommendation for Engagement


Add a "Daily Streak" counter or a Leaderboard to motivate users to
exercise every day.

iii) Clarity of Labels


Yes, the labels are easy to read because they use simple words
paired with very clear icons.
Q2.
Here is a prototype for an online fitness app. Provide
iv) Progress Chart Efficiency
feedback on how to enhance its design and functionality.
Yes, the bar chart is efficient because it allows users to compare
i) What do you think is the strongest part of the design?
their daily step counts at a single glance.
ii) What changes would you recommend to make the
prototype more engaging?
v) Additional Data
iii) Are the labels easy to read and understand? Justify your
▪ Include "Calories Burned" and "Water
answer.
Intake" to provide a better summary of daily health.
iv) Would this chart help users track workouts and progress
efficiently?
v) Is there any additional data you think should be included
to make the app more useful?

Page 90 of 102
Ser SLO Section Questions Answer
i) Strongest Part of the Design
The category icons (Pizza, Burgers, etc.) are the strongest part
because they allow users to quickly filter food choices visually.

ii) Recommendations for Engagement


Add vibrant food photos instead of gray placeholders and include a
"Limited Time Offers" section with eye-catching colors.

iii) Clarity of Labels


Yes, labels like "View Menu" and "Proceed to Checkout" are very
clear because they use standard action words that users expect.

Q3. iv) Figma or Adobe XD.


Here is a prototype for an online food delivery service.
Provide feedback on how to enhance its design and v) Additional User-Friendly Data
functionality. ▪ Include user reviews for restaurants and estimated delivery
i) What do you think is the strongest part of the design? times more prominently to help users make faster decisions.
ii) What changes would you recommend to make the
prototype more engaging?
iii) Are the labels easy to read and understand? Justify your
answer.
iv) Name one common tool used for creating interactive
prototype.
v) Is there any additional data you think should be included
to make the service more user-friendly? Explain.

Q4. Imagine a prototype of a Food Delivery App where the i) Poor Visual Hierarchy; the most important action (Confirm Order)
"Discount Coupon" text is huge and red, but the "Confirm is hidden while less important info (Coupon) is too distracting.
Order" button is small and gray at the very bottom. ii) Make the "Confirm Order" button large and a bright color (like
Green) and place it where the user doesn't have to scroll.
i) Identify the design flaw in this prototype. High Cart Abandonment; users will get confused or frustrated trying
ii) How would you fix this to increase sales? to find how to finish the order.
Predict the User Behavior if this is not fixed.
Q5. You plan to develop a School Event Management i) Three Key Features for the Prototype:
App.
i) List three key features for its prototype. • Event List Page – Displays upcoming school events with
Page 91 of 102
Ser SLO Section Questions Answer
Draw a simple sketch of the prototype layout. date, time, and brief details.
• Event Registration Option – Allows students to register for an
event.
• Notifications/Announcements Section – Shows updates and
reminders about events.
ii) Simple Sketch of the Prototype Layout (Low-Fidelity
Wireframe)

a)

42. [SLO CS-12-C-02] A Q1. Store student names as keys and a list of their marks gradebook = {
Students should be as values. Calculate the average marks for a specific "Ahmed": [80, 90, 70],
able to use more student. "Fatima": [95, 92, 98],
advanced programming "Bilal": [60, 65, 55]
constructs such as data }
structures (lists etc.), # Task: Get Fatima's marks and calculate average
file handling (disk I /O f_marks = gradebook["Fatima"]
to write to storage), and average = sum(f_marks) / len(f_marks)
databases in Python.
print(f"Fatima's Average: {average:.2f}")

# Debugging: Check if Ahmed's list has 3 marks


assert len(gradebook["Ahmed"]) == 3, "Incomplete data for Ahmed"
Page 92 of 102
Ser SLO Section Questions Answer
Q2. Create a 3 x 3 grid (nested list) representing a seating seating_plan = [
plan. Change the person in the middle seat and print ["Ali", "Sara", "Zain"], # Row 0
the updated plan. ["Hina", "Omar", "Abid"], # Row 1
["Sana", "Raza", "Huda"] # Row 2
]
print(f"Original middle person: {seating_plan[1][1]}")

# Update the middle seat


seating_plan[1][1] = "Asim"

# Print the updated row to verify


print("Updated Row 1:", seating_plan[1])
Q3. Look at the following code. It is supposed to print The Error: fruit_box[1][1] accesses the second list and the second
"Apple". Identify the error and fix it. item in that list, which is "Banana".
fruit_box = [["Orange", "Lemon"], ["Apple", "Banana"]]
print(fruit_box[1][1]) The Fix: To get "Apple", use index 0 for the inner list.

Correct Code: print(fruit_box[1][0])


Q4. What will be the output of the following Python program? ['Apple', 'Mango', 'Orange']

fruits = ["Apple", "Banana", "Mango"]


[Link]("Orange")
[Link]("Banana")
print(fruits)
Q5. The following program is meant to store student names student = {"name": "Ali", "age": 16, "grade": "A"}
and their marks in a dictionary and print the student’s grade,
but it has some errors: # Print name and grade
print("Name:", student["name"])
student = {"name": "Ali", "age": 16, "grade": "A"} print("Grade:", student["grade"])
print(student["name"])
print(student["marks"]) The original code used student["marks"], which doesn’t exist. It
should be student["grade"].
Modify the code to correctly print the student’s name and
grade. Output:
Name: Ali
Grade: A
Page 93 of 102
Ser SLO Section Questions Answer

Q6. Write a Python program to create a file named with open("[Link]", "w") as file:
[Link] and write the line [Link]("Welcome to Python Programming")
“Welcome to Python Programming” into it.
Q7. Write a Python program to open a file named with open("[Link]", "r") as file:
[Link] and display its contents. content = [Link]()
print(content)
Q8. Write a Python program that counts the number of lines with open("[Link]", "r") as file:
in a file named [Link]. lines = [Link]()
print("Number of lines:", len(lines))
Q9. Write a Python program to add the line “This is an with open("[Link]", "a") as file:
appended line.” to an existing file named [Link]. [Link]("\nThis is an appended line.")
Q10. Write a Python program that reads a text file and file = open("[Link]", "r")
prints the number of occurrences of each letter of the
alphabet (a–z), ignoring case. # Read file content
text = [Link]()

[Link]()

# Convert text to lowercase


text = [Link]()

# Loop through letters a to z


for letter in "abcdefghijklmnopqrstuvwxyz":
count = 0

# Count each letter


for ch in text:
if ch == letter:
count += 1
print(letter, ":", count)
Q11. Write a Python script to create a database named import sqlite3
[Link] and a table named Employees with columns
EmpID (Integer) and Name (Text). # Connect and create cursor
con = [Link]("[Link]")
cur = [Link]()
Page 94 of 102
Ser SLO Section Questions Answer

# Execute Table Creation


[Link]("CREATE TABLE Employees (EmpID INTEGER, Name
TEXT)")

print("Table Created Successfully.")


[Link]()
Q12. A student wrote the following code to add a record, but The student forgot the commit() statement.
the database is still empty. Identify the missing line and
rewrite the corrected loop. Corrected Code:

import sqlite3 [Link]("INSERT INTO Books VALUES ('Maths', 500)")


con = [Link]("[Link]") [Link]() # This was the missing line
cur = [Link]() [Link]()
[Link]("INSERT INTO Books VALUES ('Maths', 500)")
# Missing line here
[Link]()

Q13. Look at the code below. What error will occur, and Error:
how do you fix it?
NameError: name 'cur' is not defined.
import sqlite3
[Link]("SELECT * FROM Students") Correction:

First import the library, connect to a database, and define the cursor
(cur = [Link]())
before using it to execute commands.
Q14. Write a program to fetch and display all records from a import sqlite3
table named Inventory
con = [Link]("[Link]")
cur = [Link]()

# Execute Select Query


[Link]("SELECT * FROM Inventory")
data = [Link]()

Page 95 of 102
Ser SLO Section Questions Answer
# Loop through the records
for row in data:
print(row)

[Link]()
Q15. Using SQLite, create a table "books" with columns id, import sqlite3
title, and author. Insert 2 records, then query and display
books by a specific author. conn = [Link]("[Link]")
cursor = [Link]()

# Create table
[Link]("CREATE TABLE IF NOT EXISTS books (id
INTEGER PRIMARY KEY, title TEXT, author TEXT)")

# Insert data
[Link]("INSERT INTO books (title, author) VALUES
('Book1', 'Author1')")
[Link]("INSERT INTO books (title, author) VALUES
('Book2', 'Author2')")

# Query
author = "Author1" # In exam, this could be input
[Link]("SELECT id, title, author FROM books WHERE
author = ?", (author,))

results = [Link]()

print(f"Books by {author}:")
for row in results:
print(f"ID: {row[0]}, Title: {row[1]}, Author: {row[2]}")

[Link]()
[Link]()
43. [SLO CS-12-C-03] A Q1. Write a program that takes a list of numbers and returns def filter_evens(nums):
Students should be a new list containing only the even numbers. even_list = []
able to implement for n in nums:
Page 96 of 102
Ser SLO Section Questions Answer
complex algorithms that if n % 2 == 0:
use lists etc. in Python even_list.append(n)
return even_list

numbers = [1, 2, 3, 4, 5, 6]
print(filter_evens(numbers))
Q2. Create a dictionary of 3 items and their prices. Write a inventory = {"Apple": 0.50, "Banana": 0.30, "Orange": 0.80}
program that asks the user for an item name and prints its
price. If the item isn't found, print "Not in stock." item = input("Enter item to check: ").capitalize()

if item in inventory:
print(f"The price of {item} is ${inventory[item]}")
else:
print("Not in stock.")
Q3. Write a function that takes a list and returns both the def get_min_max(numbers):
minimum and maximum values as a tuple. return (min(numbers), max(numbers))

nums = [23, 1, 45, 99, 12]


result = get_min_max(nums)
print(f"Min: {result[0]}, Max: {result[1]}")
Q4. A teacher wants to find the student with the highest students = [
score in a class. {"name": "Ali", "score": 85},
The students’ data is stored in a list of dictionaries, where {"name": "Sara", "score": 92},
each dictionary contains the student’s name and their score. {"name": "Zain", "score": 78}
]

def find_topper(student_list):

top_student = student_list[0] # Assume the first one is the best


for s in student_list:
if s["score"] > top_student["score"]:
top_student = s
return top_student["name"]

print("Top Student:", find_topper(students))


Q5. Write a python program to calculate the transpose of a 3 matrix = [
Page 97 of 102
Ser SLO Section Questions Answer
x 3 matrix. [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Create empty matrix for transpose


transpose = [ ]

# Loop through columns and rows


for i in range(len(matrix[0])): # number of columns
row = [ ]
for j in range(len(matrix)): # number of rows
[Link](matrix[j][i])
[Link](row)

# Print transpose
print("Transpose of the matrix is:")
for row in transpose:
print(row)
Q6. Write a program using a function that sorts a list of def bubble_sort(arr):
numbers in ascending order without using any built-in sort n = len(arr)
functions. # Outer loop to traverse through all elements
for i in range(n):
# Inner loop for comparisons
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr

data = [64, 34, 25, 12, 22]


print("Sorted list:", bubble_sort(data))
44. [SLO CS-12-C-04] A Q1. The following function is calculating a total incorrectly.
Students will determine for price in prices:
more advanced def calculate_total(prices): total += price + (price * 0.10)
techniques (unit tests, total = 0 print(total)
breakpoints, watches) for price in prices:
Page 98 of 102
Ser SLO Section Questions Answer
for testing and total += price + (price * 0.10)
debugging their code in return total
Python Task: Insert one print() statement inside the loop that
displays the total every time it updates. Write the modified
loop .
Q2. You have a function that calculates the area of a square.
def get_area(side): assert get_area(4) == 16
return side * side
get_area(4)
Task: Write one line of code using assert to check if
get_area(4) results in 16.
Q3. Write one line of code to check if multiply(3, 4) is 12. assert multiply(3, 4) == 12, "Incorrect product"
Q4. You have a function that checks if a user's password is import unittest
valid (it must be at least 8 characters long).
class TestPassword([Link]):
def is_strong_password(password):
if len(password) >= 8: def test_short_password(self):
return True # We expect this to be False
else: [Link](is_strong_password("123"), False)
return False
def test_long_password(self):
Task: Using the unit test library, write a test class with two # We expect this to be True
methods: [Link](is_strong_password("password123"))

test_short_password: Checks if "123" returns False. if __name__ == '__main__':


[Link]()
test_long_password: Checks if "password123" returns True
Q5. You have a function that doubles a number. You need to import unittest
verify it works using a formal test.
class TestMath([Link]):
def double_number(n): def test_double(self):
return n * 2 [Link](double_number(5), 10)
Task: Write a single Unit Test using unittest that checks if
double number (5) correctly returns 10.
Q6. Write a function divide (a, b) that returns division result. def divide(a, b):
Write unit tests to check: return a / b
Page 99 of 102
Ser SLO Section Questions Answer
• Normal division
• Division by zero (should raise error) import unittest
class TestDivide([Link]):

def test_normal_division(self):
[Link](divide(10, 2), 5)

def test_divide_by_zero(self):
with [Link](ZeroDivisionError):
divide(10, 0)

if __name__ == "__main__":
[Link]()
45. [SLO EN-12-H-01] A Q1. You want to build a website that sells indoor plants and ii. Plant Catalog: A list of plants with prices and a "Buy" button.
Students will create and also tells people how to keep them alive based on their
test a minimum viable home’s sunlight. Light Filter: A simple dropdown menu where users can
product for their select "Low Light" or "Bright Light" to see matching plants.
business i. List two essential features for the MVP. iii. Simple layout of Home page

ii. Draw a simple layout (Wireframe) of the Homepage.

iii. Describe one way to gather feedback on this MVP.

iv. If users say "I forget to water my plants," suggest one


improvement.

v. Why is it important to use an MVP to test "User


Satisfaction"?

iv. Ask 5 friends who usually kill their plants to try and find a
plant on your site. Ask them: "Do you feel confident that this
plant will live in your house based on the info provided?"

v. Watering Alerts: Add a feature where the website sends an


automatic email or "push notification" every week to remind
the buyer to water that specific plant.
Page 100 of 102
Ser SLO Section Questions Answer
It lets you see if your solution actually solves the user's problem (keeping plan
before you spend money on a huge inventory of expensive plants.
Q2. After launching an MVP for a "Home Tutor Finder," the ii. Missing Information: The profile doesn't show the price or tutor's
data shows that 80% of users leave the site at the "Tutor qualifications clearly, so users leave to find better info.
Profile" page without booking. Slow Loading: The tutor’s profile picture or page takes too long to
load, making users lose patience and close the site.
ii. Identify two possible technical or design reasons for this iii. Clear "Book Now" Button: Place a large, brightly colored "Book
high "bounce rate." a Free Demo" button at the top of the profile so it is the first thing
iii. Propose one specific improvement to the UI/UX to fix users see.
this issue.
List three specific Success Metrics (KPIs) you would track iv. Three Success Metrics (KPIs):
during the first week of testing to decide if the MVP is • Signup Rate: How many visitors actually created an
successful. account. (Checks if they like the idea).
• Booking Rate: How many people who saw a tutor actually
booked a lesson. (Checks if the info is helpful).
• Return Rate: How many users came back to use the site
again. (Checks if the site is truly useful).

Q3. You want to create an app called "Quick Meds" that 1. Essential Feature: A searchable list of medicines with an
delivers over-the-counter medicines (like painkillers or "Order Now" button.
bandages) to people's homes within 30 minutes. 2. Tool: Shopify or Wix (using a simple e-commerce template).
1. Identify the most essential feature for the MVP. 3. Wireframe: [Draw a box showing: List of items ordered, Total
2. Name a simple tool or technology to build the Price, Address Input field, and a large "Confirm Order" button].
Frontend and Backend quickly. 4. Improvement: Add high-quality photos of the medicine
3. Draw a simple wireframe of the "Checkout" screen. (1 packaging so users can verify it visually before buying.
Mark) 5. KPI: Delivery Time Accuracy (Checking if orders actually
4. Feedback shows that users are worried about getting arrive within the promised 30 minutes).
the "wrong medicine." Suggest one UI/UX a.
improvement to fix this.
List one Success Metric (KPI) you would track in the first
week.
Q4. You want to start a "Cloud Kitchen" that sells only i. Tech Stack: WhatsApp Business: To show the menu.
three types of Biryani. You want to use an MVP to see EasyPaisa / JazzCash: To collect payments quickly.
which flavor is most popular before hiring more chefs. ii. Future Improvements:
1. Identify a "Low-Cost" technology stack for this MVP. 1. Live Tracking: A map to show where the food is.
2. Design three future improvements for the app once it 2. Weekly Plans: A "Daily Lunch" subscription for offices.
Page 101 of 102
Ser SLO Section Questions Answer
grows. 3. Reward Points: Buy 5 meals, get 1 drink free.
3. Why is MVP testing important before renting a large iii. Importance:
kitchen space? b) Saves Money: It stops you from wasting money on a big kitchen
before you know if people like your food.
Q5. You want to start a business selling T-shirts with i. A Product Catalog with a Payment/Order Button (so users can
custom slogans. Instead of building a complex website, you actually see the designs and buy them).
decide to launch a Minimum Viable Product (MVP) first. ii. Shopify (or WooCommerce) because it provides both the
i. Identify the most essential feature needed to start selling. website look (Frontend) and the order database (Backend) in
ii. Name a simple tool/technology to build the Frontend and one package.
Backend quickly. iii.
iii. After showing the site to friends, they suggest Custom Design Tool: Allow users to type their own text or upload
improvements. List three future features you would add. images onto a shirt.
Customer Reviews: A section for buyers to post photos and ratings
to build trust.
b. Size Guide/Chart: A clear table to help users pick the right fit
and reduce returns.

Page 102 of 102


Ser SLO Sec Questions Answers
A/B
1. [SLO CS-11- B Q.1 Final Simplified Answer (Using K-Map):
A-01] Simplify the Boolean Function F F=A+B+C̅
using the Karnaugh Map and also
construct the logic circuit for the
simplified expression.
F = A̅B̅C+̅ A̅BC̅+ A̅BC+ AB̅C̅ +
AB̅C+ ABC̅ + ABC

Q.2 Simplify the Boolean Function Final Simplified Answer (Using K-Map):
F using the Karnaugh Map. F=C
F=A̅BC̅ +A̅BC+AB̅C+ABC
Q.3 Simplify the Boolean Function Final Simplified Answer (Using K-Map):
F using the Karnaugh Map F=C̅
F=A̅B̅C+̅ A̅BC̅+AB̅C+̅ ABC̅
Q.4 Draw truth table of (A.B)+C (A.B)+C
0
1
0
1
0
1
1
1
2. [SLO CS-11- B Q.1 Create pseudocode to Print num1 = [number]
B-01] the largest/smallest number. num2 = [number]

IF num1 > num2 THEN


PRINT "Largest: " + num1
PRINT "Smallest: " + num2
ELSE
PRINT "Largest: " + num2
PRINT "Smallest: " + num1
Q.2 Create pseudocode to Print num = [number]
even/odd numbers.
IF num MOD 2 == 0 THEN
PRINT num + " is even"
ELSE
PRINT num + " is odd"
Q.3 Create pseudocode to Find n = [number]
the factorial of a number. fact = 1
i=1

WHILE i <= n
fact = fact * i
i=i+1

PRINT "Factorial: " + fact


Q.4 Create pseudocode to Print n = [number]
the table of a number. i=1

WHILE i <= 10
PRINT n + " x " + i + " = " + (n * i)
i=i+1
3. [SLO CS-11- B Q1. Search a given number from 1. Sort the list
B-02] the list of numbers by using binary 2. Find middle element
search. 3. Compare target with middle
4. Repeat steps 2-3 in half of the list
Q2. Search a given number from 1. Sort the list
the list of numbers by using Linear 2. Find the middle element
search. 3. Compare the target with the middle
element
4. If match, return the position
5. If target is less than middle, repeat steps 2-
4 in the left half
6. If target is greater than middle, repeat steps
2-4 in the right half
7. Continue until found or not found
Q3. Sort the list of numbers using 1. Compare adjacent elements
Bubble sort. 2. If elements are in wrong order, swap them
3. Repeat steps 1-2 until no more swaps
needed
Q.4 Sort the list of numbers using 1. Iterate through the list starting from the
Insertion sort. second element
2. Compare the current element with the
previous elements
3. Shift larger elements to the right
4. Insert the current element at its correct
position
5. Repeat steps 1-4 until the list is sorted
4. [SLO CS-11- B Q1. Design a strategy for - Identify target audience
G-01] collecting data from real-life - Prepare open-ended questions
examples using: Interviews - Conduct face-to-face or online interviews
- Record and analyze responses
Q2. Design a strategy for - Create online or paper-based
collecting data from real-life questionnaires
examples using: Surveys - Share with target audience
- Collect and analyze responses
Q3. Design a strategy for - Develop a prototype or mockup
collecting data from real-life - Test with users
examples using: Prototypes - Gather feedback and iterate
Q4. Design a strategy for - Create a simulated environment
collecting data from real-life - Test with users
examples using: Simulations - Observe and record behavior
5. [SLO CS-11- B Q1. Scatter Plot: The scatter plot shows a random distribution
D-03] of points, indicating no clear linear
import [Link] as plt relationship between X and Y.
import numpy as np

# Sample data
x = [Link](10)
y = [Link](10)
[Link](x, y)
[Link]('X')
[Link]('Y')
[Link]('Scatter Plot Example')
[Link]()

What is the relationship between


X and Y?
Q2. What is the range of X The X values range from approximately 0 to
values? 1.
Q3. What is the median Y value? To answer this, we would need to calculate
the median of the Y values: [Link](y).
Q4. Are there any outliers in the Visually inspecting the plot, there don't
data? appear to be any obvious outliers.
6. [SLO CS-12- A Q1. Write a Python program to # Open the file in write mode
C-02] create a text file named with open("[Link]", "w") as file:
"[Link]" and write the # Write the lines to the file
following lines to it [Link]("Hello, World!\n")
Hello, World! [Link]("This is a test file.\n")
This is a test file. [Link]("Python is fun!\n")
Python is fun!
Q2. Trace output: fruits = ['Apple', 'Elderberry', 'Banana', 'Cherry',
["Apple", "Banana", "Cherry"] 'Date']
[Link]("Date") ['Apple', 'Elderberry', 'Cherry', 'Date']
[Link](1, "Elderberry")
print(fruits)
[Link]("Banana")
print(fruits)
Q3. How do you establish a import sqlite3
connection to a SQLite database conn = [Link]('[Link]')
using Python?
Q4. def math_operations(num):
Write Python programs that print("Number:", num)
performs some mathematical print("Square:", num ** 2)
operations on a value passed to it. print("Cube:", num ** 3)
print("Square Root:", num ** 0.5)
math_operations(5)
7. [SLO CS-12- A Q1. Create a nested list of fruits fruits = [["Apple", "Banana", "Cherry"],
C-03] and print the second fruit in the ["Date", "Elderberry", "Fig"]]
second list. print(fruits[1][1]) # Output: Elderberry
Q2. Create a dictionary with a list person = {"name": "John", "hobbies":
as a value and print the second ["reading", "swimming", "cycling"]}
item in the list. print(person["hobbies"][1]) # Output:
swimming
Q3. What is the output of the swimming
following code?
person = {"name": "John",
"hobbies": ["reading",
"swimming", "cycling"]}
print(person["hobbies"][1])
Q4. What is the output of the Quetta
following code?
cities = [["Lahore", "Karachi",
"Islamabad"], ["Peshawar",
"Quetta", "Multan"]]
print(cities[1][1])
8. [SLO CS-12- A Q1. Write a unit test for the import unittest
C-04] add_numbers (a, b) function to
verify that it correctly adds two def add_numbers(a, b):
positive numbers. return a + b

class TestAddNumbers([Link]):
def test_add_positive_numbers(self):
result = add_numbers(2, 3)
[Link](result, 5)

if __name__ == '__main__':
[Link]()
Q2. how can you use print def calculate_average(numbers):
statements to identify the problem sum = 0
in calculate_average(numbers) for num in numbers:
function? print("num:", num)
sum = num
def calculate_average(numbers): print("sum:", sum)
sum = 0 average = sum / len(numbers)
for num in numbers: return average
sum = num
average = sum / len(numbers)
return average

numbers = [1, 2, 3, 4, 5]
print(calculate_average(numbers))
Q3. What would be the output of The output would be Error: non-numeric
the following code? input: 3

numbers = [1, 2, '3', 4, 5]


print(calculate_average(numbers))
Q4. Examine the following Errors identified and corrected:
Python program, identify any
errors, and correct them. 1. Missing closing quote in the print
rainfall=[50, 80, 60, 30, 120, 90, statement: added a closing quote after
70, 100, 85, 95, 40, 65] "average rainfall ="
avg= sum(rainfall)/12; 2. Missing comma in the print statement:
print("average rainfall = , added a comma after "average rainfall =" to
average) separate the string from the variable avg
3. Hardcoded the divisor (12) in the average
calculation: replaced 12 with len(rainfall) to
make the code more flexible and accurate, in
case the length of the rainfall list changes in
the future.
Corrected:
rainfall = [50, 80, 60, 30, 120, 90, 70, 100,
85, 95, 40, 65]
avg = sum(rainfall) / len(rainfall)
print("average rainfall =", avg)

You might also like