Computer - 11 EM
Computer - 11 EM
SCIENCE
Contents
2 Python Programming 30
4 Computational Structures 87
Answers 223
UNIT Introduction to
1 Software Development
Student Learning Outcomes
By the end of this chapter, students will be able to:
• Dene software development and explain its importance.
• Understand and describe key software development terminology, including
Software Development Life Cycle (SDLC), debugging, testicang, and design
patterns.
• Explain the stages of the SDLC and the objectives and activities involved in each
stage.
• Differentiate between various software development methodologies such as the
Waterfall model and Agile methodology.
• Plan a software project by setting timelines, estimating costs, and managing risks.
• Recognize and apply quality assurance techniques to ensure software standards.
• Utilize Unied Modeling Language (UML) diagrams to represent software systems.
• Identify and apply common software design patterns in software design.
• Employ debugging techniques and testing strategies to ensure software reliability.
• Understand and utilize various software development tools, including Integrated
Development Environment (IDEs), compilers, and source code repositories.
1
Introduction
Software development is a systematic process that transforms user needs into software
products. It involves a series of stages, from initial analysis through design, coding,
testing, and deployment. Each stage has its own importance and requires specific skills
and tools. Understanding the software development process is crucial for creating
reliable, maintainable, and scalable software solutions. This chapter introduces the
fundamental concepts of software development, including key terminology, the
Software Development Life Cycle (SDLC), software development methodologies,
project planning and management, quality assurance, and software design patterns.
1.1 Software Development
Software development is the process of creating computer programs designed to
perform specific tasks. This involves writing code, testing it, and addressing any issues
that arise. Software development is important because it helps solve problems and
makes our lives easier. For example, software allows us to communicate with friends
through social media, helps us manage our money with banking apps, and makes
learning fun with educational games.
1.2 Introduction to Software Development Life Cycle
(SDLC)
Software Development Life Cycle (SDLC) is a framework that defines the processes used
by organizations to build an application from its initial conception to its deployment and
maintenance. The primary purpose of SDLC is to deliver high-quality software that
meets or exceeds customer expectations, reaches completion within time and cost
estimates, and works efficiently.
1.2.1 Framework in Software Development
In software engineering, a framework is a standardized and reusable set of concepts,
practices, and tools that provides a structured foundation for developing software
applications. It offers predefined components and architectures that facilitate the
implementation of specific software functionalities, allowing developers to focus on
writing code specific to their application rather than reinventing common solutions.
Frameworks promote efficiency, consistency, and code reusability, thereby improving
the overall quality and maintainability of software systems.
Example: Imagine you want to create a website. Instead of writing all the code from
scratch, you can use a framework like Django (for websites). Django comes with ready-
made features like user login, database management, and page templates. This is similar
to using a pre-designed blueprint to build a house instead of designing everything
yourself.
1.2.2 Stages involved in SDLC
The SDLC is an organized method for developing software that ensures it meets quality
2
standards and functions properly. It is used by software developers and engineers to
guide the design, development, and testing of software. The SDLC consists of several
steps as shown in Figure 1.1. Each step has distinct tasks and goals.
3
Functional and Non-Functional Requirements
Requirements are generally categorized into two types, functional and nonfunctional
requirements.
Functional Requirements
Functional requirements describe the specific behaviors or functions of a system. These
requirements outline what the system should do and include tasks, services, and
functionalities that the system must perform. They define the interactions between the
system and its users or other systems.
Example:
Functional Requirements for a Library Management System.
· User Registration: The system should allow users (students, faculty) to
register and create an account.
· Book Borrowing: The system should enable users to search for books and
borrow them.
· Book Return: The system should allow users to return borrowed books.
· Inventory Management: Librarians should be able to add, update, and
remove books from the inventory.
· Notification: The system should send notifications to users about due dates
and overdue books.
Non-Functional Requirements
Non-functional requirements define the quality attributes, performance criteria, and
constraints of the system. These requirements specify how the system performs a
function rather than what the system should do. They include aspects like usability,
reliability, performance, and security.
Example:
Non-Functional Requirements for a Library Management System.
· Performance: The system should handle up to 1000 simultaneous users without
performance degradation.
· Usability: The user interface should be intuitive and easy to navigate, allowing
users to perform tasks with minimal effort.
· Reliability: The system should be available 99.9% of the time, ensuring high
availability and minimal downtime.
· Security: User data should be encrypted, and access should be controlled
through secure authentication mechanisms.
· Scalability: The system should be able to scale to accommodate an increasing
number of users and books in the inventory.
4
Differentiating Functional and Non Functional Requirements:
Functional Requirements Non-Functional Requirements
Define specific behaviors or functions of Define the quality attributes and constraints -
Think of this phase like designing a new house. You need blueprints to show where the
rooms and furniture will go before you start building.
1.1.1.1 Development
In the development phase, the actual creation of the software begins. This is where
programmers write the code, which is a set of instructions that the computer follows to
perform specific tasks. Based on the design specifications, which outline what the
software should do and how it should look, programmers translate these specifications
into a programming language. 5
Think of it like following a recipe: the design specifications are the recipe, and coding is
the process of mixing and baking the ingredients to make a cake. Each line of code is like
a step in the recipe, ensuring the software works conectly and meets the requirements
set out in the design. During this phase, programmers also test their code to find and fix
any errors or bugs. This testing helps ensure that the software performs as expected and
is free from mistakes. If any issues are found, programmers revise the code, correct the
problems, and test again until the software is ready for the next stage.
1.1.1.2 Testing
Once the software has been developed, it undergoes a crucial phase called testing.
Testing is the process of checking the software to identify any bugs, errors, or issues.
Think of it as a quality check to make sure everything works as expected. During testing,
the software is run under various conditions to see if it behaves correctly. This includes:
· Functionality Testing: Ensuring all features of the software work according
to the specifications.
· Performance Testing: Checking if the software performs well under different
conditions, such as high traffic or heavy data.
· Compatibility Testing: Making sure the software works well on various
devices and operating systems.
Testing helps in identifying any hidden issues that were not apparent during
development. By fixing these issues, developers ensure that the software runs smoothly
and meets the user's needs, providing a better and more reliable experience.
1.1.1.3 Deployment
Once the software has been thoroughly tested and any issues have been fixed, it moves
to the deployment phase. Deployment is the process of making the software available
for users to access and use. This often involves several steps:
· Installation: The software is installed on the user's system or server. This may
involve running an installation program that copies files and sets up
necessary configurations.
· Configuration: The software is adjusted to fit the specific needs of the user
or organization. This can include setting up user preferences, network
settings, and database connections.
· Testing in the Real World: After installation, the software is tested in its real-
world environment to ensure it works correctly with other systems and meets
user needs.
6
1.1.1.1 Maintenance
The final phase involves ongoing maintenance and updates. This ensures the software
continues to function correctly and adapts to any changes in user needs or technology.
Maintenance is like taking care of a plant. You need to water it regularly and address any
problems to keep it healthy and growing.
13
1.4.1 Comprehensive Project Planning
Comprehensive project planning involves thinking about all the details of your project
before you start. This includes understanding what needs to be done, who will do it, and
how it will be done.
Some of the largest software development companies in the world
are worth billions of dollars! For example, as of 2023, Microsoft, one of
the leading software giants, has a market capitalization exceeding $2
trillion. This immense value highlights the significant impact and
economic importance of software development in today's digital age.
Cost Breakdown:
· Project Manager:
PKR 5,000/hour x 20hours/week x 24 weeks = PKR 2,400,000
· Frontend Developers:
2developers x PKR 3,500/hour x 30hours/week x 24weeks = PKR 5,040,000
· Backend Developers:
2developers x PKR 4,000/hour x 30hours/week x 24weeks = PKR 5,760,000
· UI/UX Designer:
PKR 3,000/hour x 20hours/week x 24 weeks = PKR 1,440,000
· QA Testers:
testers x PKR 2,500/hour x 20hours/week x 24 weeks = PKR 2,400,000
· Operational Costs:
Cloud services and tools = PKR 1,000,000
· Contingency Fund:
10% of the total estimated cost = PKR 1,604,000
Total Estimated Cost: PKR 19,644,000
Explanation: The total estimated cost of PKR 19,644,000 includes all aspects of
development, from planning and design to implementation and testing. This example
illustrates how different factors contribute to the overall cost and the importance of
detailed planning in cost estimation.
You don't need to know programming to start a software development project! You can
post your idea on freelancing platforms where developers can bid on your project. With
the help of your family, you can also seek out investors to fund your idea. This way, you can
bring your vision to life with professional help and turn your innovative ideas into reality!
15
1.1.1 Risk Assessment and Management
Risk assessment and management are crucial aspects of any software project. They
involve identifying potential risks that could impact the project's success, analysing the
likelihood and impact of these risks, and developing strategies to manage them.
Effective risk management helps ensure that projects stay on track, within budget, and
meet quality standards.
Steps in Risk Assessment and Management:
1. Identify Risks: List all potential risks that could affect the project. These could be
technical risks, such as technology changes; operational risks, like resource
shortages; or external risks, such as market fluctuations.
2. Analyze Risks: Evaluate the likelihood of each risk occurring and its potential
impact on the project. This helps in prioritizing which risks need more attention.
3. Develop Mitigation Strategies: For each significant risk, develop a plan to
reduce its likelihood or minimize its impact. This could involve adding buffers to
the schedule, securing backup resources, or conducting additional testing.
4. Monitor and Review: Continuously monitor the project for new risks and
review existing risks to adjust strategies as necessary.
Example: A project is using a new, untested technology. The risk is that the technology
may not work as expected, causing delays and additional costs.
Mitigation Strategy: Conduct a small-scale pilot project to test the technology before
fully integrating it into the main project. This can help identify potential issues early and
provide a chance to address them without impacting the larger project.
Discussion: Figure 1.8 illustrates the risk management process, showing the steps from
identifying risks to monitoring and reviewing them. By following these steps, project
managers can systematically address risks, ensuring a smoother project execution.
1.1.2 Quality Assurance
Quality assurance ensures that a project meets set standards and works correctly. It
involves methods such as testing, reviewing code, getting feedback from stakeholders,
and regularly checking the project's progress.
Example: In a software project, this involves ensuring that the code is both accurately
written and functions as expected.
1.2 Graphical Representation of Software Systems
Graphical representation of software systems involves using visual diagrams to depict
various aspects of a software system's structure and behavior. This approach helps in
simplifying complex systems, making it easier for developers and stakeholders to
understand, communicate, and manage the system. Diagrams, like Unified Modeling
Language (UML) diagrams, are widely used to illustrate various components, their
16
relationships, and interactions within software.
1.2.1 Introduction to UML
Unified Modeling Language (UML) is a standardized way to visualize the design of a
software system. It helps developers understand how a system works and
communicates. UML is important because it makes complex systems easier to
understand and manage.
Class Activity
Objective: Learn to identify actors and use cases from a given statement
describing a system.
Instructions:
1. Read the following statement carefully.
2. Identify the actors involved in the system.
3. Identify the use cases that describe the interactions between the
actors and the system.
4. Write down your findings and be prepared to discuss them with the
class.
18
Class Activity
Statement: Imagine you are designing an online shopping platform. The
platform allows customers to browse products, add items to their cart, and
make purchases. Additionally, the platform includes features for
administrators to manage product listings, process orders, and handle
customer inquiries. There is also a feature for delivery personnel to update the
status of deliveries.
In the above class activity, you can compare your findings with the
following:
· Actors:
o Customer
o Administrator
o Delivery Personnel
· Use Cases:
o Browse Products
o Add Items to Cart
o Make Purchase
o Manage Product Listings
o Process Orders
o Handle Customer Inquiries
o Update Delivery Status
1.1.1.1 What is a Class Diagram?
A class diagram is like a map that shows how things are organized in a system, just like
how you organize your room. It helps us see what's in each box (like your toys, books, or
clothes) and how these boxes are related.
Example:
In the example of s organizing your room:
· Room: Represents the overall space encompassing all other elements,
analogous to the main structure in a class diagram.
· Box: Serves as a container within the room, akin to a class in a
diagram.
· Attributes: Each box contains specific items, such as a 'ToyBox'
holding toys or a 'BookBox' containing books.
· Methods: Boxes can perform actions like 'open' or 'close,' similar to
methods in a class diagram that define what the box can do.
· Specific Boxes: Examples of specialized boxes include a 'ToyBox' for
toys, a 'BookBox' for books, and a 'ClothesBox' for clothes, representing
distinct instances of the general 'Box' class.
So, a class diagram is simply a way to organize and show how different parts of a system
(like your room) work together, making it easier to understand everything at a glance as
show in Figure 1.10.
19
Figure 1.10: Class Diagram for Organizing Your Room
1.1.1.1 Sequence Diagrams
Sequence Diagrams show how objects in a system interact with each other in a particular
sequence. They help in understanding the flow of messages between objects over time.
Interactions:
· open(): User opens each box.
· put toys/books/clothes inside: User puts the respective items into the
boxes.
· close(): User closes each box.
Figure 1.11: Sequence diagram of the user organizing items into labeled boxes
20
1.1.1.1 Activity Diagrams
Activity Diagrams illustrate the flow of activities or steps in a process. They are useful for
modeling the logic of complex operations.
Example: In a restaurant management system, an activity diagram can represent the
process from 'Order Placement' to 'Food Preparation' and finally to 'Order Delivery'.
Above activity diagram shows how a process flows from start to finish. In the restaurant
management system example, the process begins with ‗Start' moves to ‗Order
Placement,' then to ‗Food Preparation,' and finally to ‗Order Delivery.' The ‗End' node
concludes the process. Arrows indicate the sequence of these steps, making it easy to
follow how an order progresses.
1.5.3 Using UML to Represent Software Systems
UML can be used in various stages of software development to improve understanding
and communication. Here are some practical applications:
• Planning: Use UML diagrams to map out the system's requirements and design
before writing any code.
• Development: Developers refer to UML diagrams to understand the structure and
relationships within the system.
• Communication: UML diagrams help team members, including non-technical
stakeholders, to understand how the system works.
21
1.6 Introduction to Design Patterns
Design patterns are a fundamental concept in software development, providing proven
solutions to common problems that arise during software development. They serve as
blueprints or templates that can be adapted to solve various design challenges, making
the development process more efficient and consistent.
22
1.6.2 Applications of Design Patterns in Software Design
Design patterns are widely used in software development to solve common problems
and create robust and maintainable code. They help in:
· Reducing code complexity by providing a clear structure.
· Enhancing code reusability by using proven solutions.
· Improving communication among developers by providing a common
vocabulary.
Design patterns help create systems that are flexible, maintainable, and easy to
understand.
29
UNIT
Python Programming
2
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Understand basic programming concepts and set up a Python development
environment.
· Write and interpret basic Python syntax and structure, including variables, data
types, and input/output operations.
· Use various operators and expressions in Python, including arithmetic,
comparison, and logical operators.
· Implement control structures such as decision-making statements and loops in
Python.
· Work with Python modules, functions, and built-in data structures like lists.
· Apply modular programming techniques and object-oriented programming
concepts in Python.
· Handle exceptions, perform file operations, and apply testing and debugging
techniques in Python.
30
Introduction
Welcome to the world of Python programming! Python is a popular, versatile language
known for its simplicity and readability, making it ideal for both beginners and
professionals. In this chapter, we will start with the basics, including setting up your
development environment and learning fundamental programming concepts. As we
move forward, we'll cover advanced topics like modular programming, file handling,
debugging, and data structures. By the end of this chapter, you will have a
comprehensive understanding of Python, enabling you to write, test, and debug your
own programs and Command Line Interface(CLI) applications.
2.1 Introduction to Python Programming
Python is a widely-used high-level programming language celebrated for its simplicity
and readability. It is versatile and applicable to various fields, including web
development, data analysis, artificial intelligence, and more. Python's straightforward
syntax and clear structure make it an excellent choice for beginners, allowing them to
focus on learning programming concepts rather than dealing with complex syntax rules.
Whether you're creating a simple script or developing sophisticated software, Python's
user-friendly nature helps you get started quickly and efficiently.
When installing Python, make sure to check the box that says "Add Python to PATH." This
makes it easier to run Python from the command line. We can also use oniline services to
write and run Python program.
Always use meaningful names for variables to make your code easier to understand. For
example, use age instead of a.
• It's a good practice to use lowercase letters and underscores to separate words in
variable names (e.g., student_name). This style is known as snake_case.
• Remember, strings in Python are always enclosed in quotes, either single (' ' ) or
double (" ").
Integer Inputs
# Example : Handling integer input
user_age = int(input("Ent er your age: "))
print("Your age is:",user_age)
Float Inputs
# Example: Handling float input
user_height = float(input("Enter your height in meters: ") )
print("Your height is", user_height,"meter")
2.3 Operators and Expressions
Operators are symbols that perform operations on variables and values. An expression is
a combination of variables, operators, and values that produces a result. Let's explore
different types of operators in Python.
1.2.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, modulus, exponentiation, and floor
division as shown in the following code. The code shows how to use basic arithmetic
operations in Python.
# Define variables
a= 10 b= 3
# Perform all arithmetic operations on these numeric variables
and print results
print(a, "+", b, "=", a + b) # Output: 10+3=13
print(a, "*", b, " = " , a * b) # Output: 10 * 3 = 30
print(a, "/", b, " = ", a / b)
34
# Output: 10 / 3 = 3.3333333333333335
print(a, "//", b, " = ", a // b)
# Output: 10 // 3=3
print(a, "%", b, " = ", a % b)
# Output: 10 % 3 = 1
print(a, "**", b, " = ", a ** b)
# Output: 10**3= 1000
35
1.1.2 Assignment Operators
Assignment operators are used to assign values to variables. The most common
assignment operator is the equal sign (=), which assigns the value on the right to the
variable on the left. There are also compound assignment operators like +=, -=, *=, and
/=, which combine arithmetic operations with assignment.
Above code illustrates the use of assignment operators in Python. The code comments
show the output of each operation.
1.1.3 Logical Operators
Logical operators are used to combine multiple conditions or expressions in a program.
The most common logical operators are and. or, and not. They are used to perform
logical operations and return Boolean values based on the evaluation of the expressions
involved.
# Define variables
x = True
y = False
# Logical AND
logical_and = x and y
print(x , "and ", y ,"=", logical_and) # Output: True and False =False
# Logical OR
logical_or = x or y
print(x , "or " , y , " =", logical_or) # Output: True and False = True
36
# Logical NOT
logical_not_x = not x
print("not", x, " = " , logical_not_x) # Output not True= False
logical_not_y = not y
print("not", y, "=" , logical_not_y)
# Output: not False= True
The above code demonstrates the use of logical operators in Python. It defines two
Boolean variables, x and y, and performs logical operations such as AND, OR, and NOT
on them. The code also includes comments with the output of each logical operation.
2.3.5 Expressions
An expression is a combination of variables, operators, and values that produces a result.
For example, 3 + 4 is an expression that results in 7. More complex expressions can use
parentheses O to control the order of operations. For example:
result = (3 + 4) * 2 # result is 14
Class Activity
Write a program to calculate Body Mass Index (BMI). Ask the user for their
weight and height, then compute and display their BMI and classification.
The Body Mass Index (BMI) is calculated using the formula given below.
weight
BMI =
height
where:
· weight is in kilograms (kg)
· height is in meters (m)
Explanation: In this example, the code goes through each friend in the list and prints a
greeting message for each one.
Example 2: Calculate total price of items in a shopping cart
41
cart = [
{"item": "Apple", "price": 0.5, "quantity": 4},
{"item": "Banana", "price": 0.2, "quantity": 10},
{"item": "Orange", "price": 0.75, "quantity": 3}
]
total_price = 0
for product in cart:
item_total = product["price"] * product["quantity"]
total_price += item_total
print(f"{product['item']} total: ${item_total:.2f}")
print (f "Total price of all items: ${total_price:.2 f}")
Output
Apple total: $2.00
Banana total: $2.00
Orange total: $2.25
Total price of all items: $6.25
Class Activity
Write a Python program that iterates over a list of temperatures and prints
“Warm” for temperatures above 20 degrees and “Cold” for temperatures 20
degrees or below.
Explanation: The above code generates numbers from 0 to 4 and prints each number.
42
Class Activity
1. Write a for loop using range() to print the even numbers from 2 to 10.
2. Write a Python program that prints the first 10 multiples of 3 using a for
loop and the range() function.
43
2.5.1.3 Default Parameters
Functions can have default parameter values, which are used if no argument is provided
during the function call.
Example: Define a function with a default parameter.
Explanation: The statistics library is a great tool for performing basic statistical
calculations, such as finding the mean, median, and mode of a set of data. This can be
particularly useful in data analysis tasks.
In short by using these libraries, you can save time and effort, allowing you to focus on
solving the specific problem at hand rather than reinventing the wheel.
45
When importing libraries, make sure to only import what you need. You can explore the
more libraries at https: //docs .python, org/3/
Class Activity
Write a Python program that imports the random and statistics libraries. Use
random to generate a list of 10 random numbers between 1 and 50. Then, use
statistics to calculate and print the mean (average) of those numbers.
import random
number = random.randint(1, 10)
print(f"Random number: {number}") # ‘f’ is used to place the value of a variable in a
string
# Output:
# Random number: 7 (or any number between 1 and 10)
46
Explanation: Here, random is part of Python's standard library, so it is found without any
issues.
Package Structure:
To manage large projects, you can organize modules into packages. A package is simply
a directory containing related modules. For example, if you're building an e-commerce
platform, you could create a package named ecommerce with modules like products
.py, customers .py, and orders.py.
Example: In ecommerce/products.py:
def 1ist_products () :
return ["Laptop","Mobile", "Tablet"]
In your main Script
from ecommerce import products
available_products = products.list_products()
print(available_products)
# Output :
# [’Laptop’, ’Mobile’, ’Tablet’]
Explanation: In this case, ecommerce is the package, and products.py is the module.
This structure helps you keep your code organized and manageable.
Organizing your modules into packages is like organizing books into sections of a
library—it makes finding and maintaining your code much easier.
Explanation: The code initializes a list 'fruits' containing 'Mango', 'Apple', and 'Banana',
then prints the second item, 'Apple', using the index ' 1 '.
2.6.1.3 Modifying a List
You can modify list items by accessing them via their index and assigning a new value.
Example: Change the first item in the list to "Orange" and add a new fruit "Pineapple".
fruits = ["Mango", "Apple", "Banana"]
fruits [0] = "Orange"
fruits.append("Pineapple")
print(fruits)
# Output: [’Orange’, ’Apple’, ’Banana’, ’Pineapple’]
Explanation: The code modifies the first element of the 'fruits' list to 'Orange', appends
'Pineapple' at the end, and prints the updated list.
2.6.1.4 Methods and Operations on Lists
Python provides several built-in methods to work with lists. Here are a few useful ones:
• append (item) - Adds an item to the end of the list.
• remove (item) - Removes the first occurrence of an item from the list.
• sort () - Sorts the list in ascending order.
• reverse () - Reverses the order of the list.
Example: Add a new student to the list of students and then sort the list.
students = ["Ahmed", "Sara", "Ali"]
students.append("Hina")
students.sort ()
print(students)
# Output : [’Ahmed’, ’Ali’, ’Hina’, ’Sara’]
Explanation: The code creates a list of students, adds 'Hina' to it, sorts the list
alphabetically.
48
2.6.1.5 List Operations
Lists also support various operations, such as slicing and concatenation.
Example: Slice a portion of the list and concatenate it with another list.
numbers = [1, 2, 3, 4, 5]
slice = numbers [1:4] # Gets items from index 1 to 3
extra_numbers = [6, 7]
combined = slice + extra_numbers
print(combined)
# Output : [2, 3, 4, 6, 7]
Explanation: The code slices the 'numbers' list from index 1 to 3, combines it with
'extra_numbers', and prints the resulting list '[2, 3, 4, 6. 7]'.
Example: Sort a list of student names and remove a specific name.
Use list methods like append() and remove () to efficiently manage and modify your lists.
For larger projects, organizing data in lists helps keep your code clean and manageable.
49
2.6.2 Tuples
In Python, tuples are a type of data structure used to store an ordered collection of
items, similar to lists, but with a key difference: tuples are immutable, meaning their
values cannot be changed after creation.
Example
# Creating a tuple
my_tuple = (1, 2, 3, "Hello", 4.5)
# Tuple length
print(len(my_tuple)) # Output: 5
Indexing and slicing are powerful tools for working with sequences in Python. Practice
these techniques to become more proficient in manipulating data and accessing specific
parts of sequences.
Explanation: In this example, the main() function will only run if the script is executed
directly, not when it's imported elsewhere. This setup is useful in larger projects that
have multiple modules.
2.7.1 Working with Modules in Python
A module in Python is just a file that contains Python code, such as functions, variables,
and classes, which you can reuse in different parts of your program. Creating a module is
easy. Just write your Python code in a file and save it with a .py extension. Here's how to
create and use a module with the main, function:
Step 1: Create a module file named greetings .py.
# greetings.py
def say_As-Salaam-Alaikum () :
return "As - Salaam-Alaikum, everyone!"
Explanation: This creates a module called greetings with a function named say_As-
Salaam-Alaikum.
Step 2: Create another file named main. py to use this module. This file will contain the
main function, which is the starting point of your program:
# main.py
import greetings
def main () :
message = greetings.say_As- Salaam-Alaikum()
print(message)
if _ _name_ _ == "_ _main_ _": main ()
# Output : As - Salaam-Alaikum , everyone!
Explanation: In this example, when you run main.py. Python imports the greetings
module, calls the say_As-Salaam-Alaikum function, and prints the message. By
organizing your program this way, you can use the greetings module in other parts of
your application, and the main function clearly shows where your program begins.
52
Using the main function with modules helps keep your code organized, making it easier
to maintain. Always use the main function to define the starting point of your program,
and use modules to separate different parts of your code.
Class Activity
Create a Python module named calculator .py that includes two functions:
1. add (a, b) - This function should return the sum of two numbers.
2. subtract (a, b) - This function should return the difference
between two numbers. Then, write a script named main. py that
imports your calculator module and uses these functions to perform
the following:
1. Print the result of adding 15 and 8.
2. Print the result of subtracting 10 from 25.
Make sure to run your main. py script and verify that the output is correct.
The destructor here prints a message when the object is deleted, indicating cleanup.
Explanation: The 'Car' class initializes with a 'color' attribute and prints a message when
an instance is deleted, indicating the car with the given color is being removed.
55
2.8.1.4 Association
Association represents a relationship between two classes. There are two types of
association:
• Aggregation: Represents a relationship where one class (e.g., Library) contains
another class (e.g., Book) but does not own it. Books can exist independently of the
library.
class Book :
def __init__(self , title):
self.title = title
class Library :
def __init__(self ) :
self, books = [ ]
def add_book(self, book):
self.books.append(book)
print("Book ", book.title, "added to the library.”)
Explanation: The above code made association by passing an instance of the 'Book'
class to the 'Library' class through the 'add_book' method, which appends the book to
the library's list of books.
Composition: Represents a relationship where one class (e.g., House) contains and
owns another class (e.g.. Room). Rooms cannot exist without a house.
class Room:
def __init__(self, name):
self.name = name
class House :
def __init__(self) :
self.rooms = [Room("Living Room"), Room( " Bedroom")]
print (“House with rooms created”)
Summary
In this chapter, we learn the essentials of Python programming, starting from the setup
of your development environment to advanced programming techniques. We explored
basic syntax, operators, and control structures, providing you with the tools to write
effective Python code. You learned how to use functions, modules, and data structures
to manage and manipulate data efficiently. We also introduced key concepts of modular
programming and object-oriented programming. Lastly, we discussed exception
handling, file operations, and debugging methods to help you troubleshoot and refine
your code. With these skills, you are well-equipped to tackle more complex
programming tasks and build robust Python CLI applications.
61
2. What should you do when installing Python to run it from the command line more
easily?
a) Uncheck "Add Python to PATH"
b) Choose a different IDE
c) Check "Add Python to PATH"
d) Install only the IDE
3. Which of the following is a valid variable name in Python?
(a) variablel
(b) Ivariable
(c) variable-name
(d) variable name
4. What is the output of the below code?
age = 25; pr int (" Age : " , age)
(a) Age: 25
(b) 25
(c) Age
(d) age
5. Which of the following operators is used for exponentiation in Python?
(a) *
(b) **
© (O //
(d) 7.
6. Which loop type in Python is used to iterate over a collection such as lists?
(a) while
(b) for
(c) do-while
(d) repeat
7. What does the range () function do in Python?
(a) Generates a list of numbers
(b) Creates a sequence of numbers
(c) Calculates the sum of numbers
(d) Prints a range of numbers
8. Which keyword is used to define a function in Python?
a) define
b) function
c) def
d) func
62
9. What is the output of the below code?
temperature, humidity, wind_speed =25, 60, 15
print("Hot and humid" if temperature > 30 and humidity > 50 else
"Warm and breezy" if temperature == 25 and wind_speed > 10 else
"Cool and dry" if temperature < 20 and humidity < 30 else
"Moderate ")
(a) Hot
(b) Warm
(c) Cool
(d) Nothing
10. Which operation is used to combine two lists?
(a) combine()
(b) concatO
(c) +
(d) merge ()
Short Questions
1. Explain the purpose of using comments in Python code?
2. Describe the difference between integer and float data types in Python. Provide an
example of each.
3. Define operator precedence and give an example of an expression where operator
precedence affects the result.
4. How does the short hand if-else statement differ from the regular if-else statement?
5. Explain the use of the range() function in a for loop?
6. Explain how default parameters work in Python functions.
7. Explain why modular programming is useful in Python.
8. Explain the difference between a class and an object in Python.
Long Questions
1. Evaluate the following Python expressions.
(a) (18 / 3 +4 ** 2) - (2 * (7 - 3)) /(9 7, 4)
(b) (25 + 3 * 4 ** 2 - 6) / (2 ** 3 + 1)- 7
(c) (12 + 6 *(5-2)) ** 2 / ((4 ** 2 - 7) + 10)
(d) 45 / (2 ** 2 + 3 * 4) + 8 * (7 - 3)
(e) (14 *3 +5 ** 2 - 28) / (4 +2 ** 3) + 10 7. 3
2. Translating the following Mathematical Expressions to Python Syntax
3. (a)
15 x (3 + 22)
6-2x3
63
(b)
7 + 22 1 7
(c)
12 + 5x4—(3+7) 2
2
2 x (5 - 24)
(d)
9x (23 + l)-15 + 3
(5 + 4) x (2 + 3) ~
4. Explain the concept of variables in Python.
5. Write a Python program that takes a number as input and checks whether
it is positive, negative, or zero using an if-elif-else statement.
6. Write a Python program using a while loop that prints all the odd numbers
between 1 and Also, count and print the total number of odd numbers.
7. Create a Python module named temperature_converter. py that includes
two functions:
(a) celsius_to_fahrenheit (c) - This function should convert a temperature from
Celsius to Fahrenheit using the formula F=|xC + 32.
(b) fahrenheit_to_celsius(f) - This function should convert a temperature from
Fahrenheit to Celsius using the formula C = | x (F — 32).
Then, write a script named main.py that imports your temperature_converter
module and uses these functions to perform the following:
(a) Convert 25 °C to Fahrenheit and print the result.
(b) Convert 77°F to Celsius and print the result.
64
UNIT Algorithms and Problem
3 Solving
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Describe and classify computational problems.
· Explain the importance of algorithms in problem-solving.
· Apply the generate and test method to solve problems.
· Differentiate between solvable and unsolvable problems.
· Understand problem complexity and categorize problems (P, NP, NP-Hard, NP-
Complete).
· Identify common computational problems like sorting and searching.
· Use algorithm design techniques like divide and conquer, greedy methods, and
dynamic programming.
· Implement and compare algorithms such as Bubble Sort, Binary Search, BFS,
and DFS.
· Evaluate algorithms based on efficiency and scalability.
· Develop algorithmic thinking to solve problems systematically.
65
Introduction
In this chapter, we will explore how to solve problems using algorithms, which are step-
by-step instructions for performing tasks. Understanding algorithms is essential not
only for computer science but also for everyday problem-solving. We will start by
learning what computational problems are and how to describe them clearly. Then, we
will look at different types of algorithms and how they can help us solve various kinds of
problems. We will also discuss how to measure the efficiency of algorithms to find the
best solutions. By the end of this chapter, you'll have the skills to think systematically and
create effective solutions using algorithms.
3.1 Understanding Computational Problems
A computational problem is a challenge that can be solved through a computational
process, which involves using an algorithm, i.e., a set of step-by-step instructions that a
computer can execute. The objective is to find a solution by following a finite sequence
of steps that a computer can perform.
• Input: The problem starts with an input, which is the data or information given to
the algorithm.
• Output: The solution or result produced by the algorithm after processing the
input.
• Process: The steps or rules (algorithm) that are applied to the input to generate
the output.
3.1.1 Characterizing Computational Problems
To solve a problem computationally, we need to understand its characteristics. This
involves identifying the inputs, the desired outputs, and the process needed to
transform the inputs into outputs.
3.1.1.1 Classifying Computational Problems
Computational problems can be classified into different categories based on their
characteristics and the methods required to solve them. Some common classifications
include:
· Decision Problems: Problems where the output is a simple “yes” or “no”.
· Search Problems: Problems where the task is to find a solution or an item that
meets certain criteria.
· Optimization Problems: Problems where the goal is to find the best solution
according to some criteria.
· Counting Problems: Problems where the objective is to count the number of
ways certain conditions can be met.
3.1.1.2 Well-defined vs. ill-defined Problems
Problems can also be categorized based on how clearly they are defined:
· Well-defined Problems: These problems have clear goals, inputs, processes, and
66
outputs. For instance, the problem of determining if a number is even, is a well-
defined problem because it has a clear goal (determine if the number is even), clear
input (a single integer), a clear process (check if the number is divisible by 2), and a
clear output (even or odd) as shown in Figure 3.1.
· Ill-defined Problems: These problems lack clear definitions or may have
ambiguous goals and requirements. For instance, consider a project aimed at
“improving education in Pakistan”. This goal is vague and broad. The input might
include resources such as funding, teachers, and educational materials, but without
clear specifications on how much funding is needed, what kind of teachers are
required, or which educational materials are most effective.
Class Activity
Students will explore route optimization by drawing maps of their city that
include several colleges. Each student will create a map, marking at least five
colleges and assigning distances between them. The goal is to plan the
shortest possible route to visit each college exactly once and return to the
starting point.
67
3.2 Algorithms for Problem Solving
Algorithms are step-by-step procedures for solving problems, much like a recipe
provides steps for cooking a dish. They form the backbone of computer science,
enabling machines to perform tasks efficiently. Understanding algorithms is essential
because they provide the logic behind software operations, allowing us to solve
complex problems, optimize performance, and ensure accuracy in various applications.
When learning about algorithms, try to relate them to real-life tasks you already know.
This will help you understand how algorithms work and why they are important.
When tackling complex problems, it's essential to first determine whether the problem is
solvable. This saves time and resources by ensuring you are working on a problem that
can be resolved using an algorithm.
71
How It Works
To sort the list [4, 1, 3, 2, 5], a computer might follow these steps:
1. Compare the first number with the second number. Swap them if needed.
2. Move to the next pair and repeat the process.
3. Continue until the entire list is sorted.
The time required to sort the list grows at a manageable rate as the list size increases. For
example, going from 5 numbers to 10 numbers will increase the time, but it remains
within a reasonable limit.
3.3.3.2 Class NP
Class NP refers to a category of problems for which, if a solution is given, it can be
checked quickly by a computer. These are problems where verifying a proposed solution
is easy, but finding that solution might be
difficult and time-consuming.
Example:
Consider a common example of solving a Sudoku puzzle. In Sudoku, you fill a 9 x 9 grid
with numbers so that each row, column, and 3 x 3 sub grid contains all digits from 1 to 9
exactly once as shown in Figure 3.5.
Class NP and Sudoku
· Verification is Easy: If someone gives you a completed Sudoku grid,
· you can quickly check if the solution is correct. You just need to ensure that each
row, column, and 3 x 3 sub grid contains all numbers from 1 to 9 without
repeating.
· Finding the Solution is Hard: Solving Sudoku from scratch, especially larger or
more complex puzzles, can be difficult and time-consuming. There is no simple,
fast way to guarantee a solution, which means finding the solution is not always
efficient.
· Non-deterministic Polynomial Time: Class NP problems can be solved quickly
if given a correct solution, but finding that solution might take an impractically
long time for large problems.
How It Works
In the context of Sudoku:
1. Checking a Solution: To verify if a Sudoku solution is correct, you can quickly
check each row, column, and subgrid to ensure they all have numbers 1 through 9
without repetition. This verification process is straightforward and efficient.
Solving the Puzzle: Finding the correct arrangement of numbers for a Sudoku puzzle
can be challenging. There are many possible configurations, and determining the
correct one involves lot of trial and error or advanced algorithm.
72
Figure 3.3: A simple Sudoku Puzzle
3.3.3.3 Class NP-Hard
NP-hard problems are a class of problems that are at least as difficult as the hardest
problems in NP (Non-deterministic Polynomial time). Solving an NP-hard problem is
challenging, and no efficient algorithm is known for finding a solution. These problems
are usually very difficult and take a lot of time to solve, even when the cases are not very
large.
Example:
A well-known example of an NP-hard problem is the Traveling Salesman Problem (TSP),
we discussed in Section 3.3.2.
Why TSP is NP-Hard
· No Known Efficient Solution: There is no known algorithm that can solve
TSP quickly for large numbers of cities. As the number of cities increases, the
number of possible routes grows factorially, making the problem extremely
difficult to solve exactly.
· Computational Complexity: The time required to solve TSP grows so quickly
with the number of cities that it becomes impractical to compute the exact
solution for large instances. For example, with just 10 cities, there are
3,628,800 possible routes.
Illustration of Complexity
Figure 3.4 Venn diagram of the complexity classes P, NP, NP-hard, and NP-complete.
74
Figure 3.4 shows a Venn diagram of the complexity classes P, NP, NP-hard, and NP-
complete. It visually represents the relationships between these classes, highlighting
how some problems can be solved efficiently, while others pose significant challenges
to computational theory.
The question of whether P equals NP is one of the most important
unsolved problems in computer science. It has significant
implications for cryptography, algorithm design, and the overall
understanding of computational complexity.Figure 3.4: Venn
Diagram of Complexity Classes P, NP, NP-hard, and NP-complete
77
3.5 Algorithm Efficiency and Scalability
3.5.1 Efficiency
Algorithm efficiency refers to how well an algorithm uses resources like time and space
(memory) to solve a problem. The efficiency of an algorithm is typically evaluated based
on its time complexity (how the run time increases as the input size increases) and space
complexity (how the memory usage grows as the input size increases).
Example: Consider two sorting algorithms: Bubble Sort and Merge Sort. Bubble Sort
has a time complexity of O(n2), meaning that if the input size doubles, the time taken
increases by four times. Merge Sort, however, has a time complexity of O(nlog n), which
grows much more slowly as the input size increases, making it more efficient for large
datasets.
3.5.2 Scalability
Scalability refers to an algorithm's ability to maintain its efficiency as the size of the input
data grows. An algorithm that scales well will perform efficiently even when the input
data is significantly larger than what it was initially designed for.
3.5.3 Suitability for Specific Problems
Not all algorithms are suitable for all types of problems. The choice of algorithm
depends on the problem's specific requirements, such as the
need for speed, memory usage, or the nature of the data.
Example: Imagine you're looking for a book in a small, unorganized collection. The best
way is to check each book one by one, this is a Linear Search. Now, if your books are
neatly arranged alphabetically on a shelf, you can quickly find the book by starting in the
middle and deciding which half to search, this is a Binary Search.
3.6 Algorithm Design Techniques
Algorithm design is a critical aspect of problem-solving in computer science. It involves
creating systematic methods to solve problems efficiently and effectively. There are
several well-known algorithm design techniques that help in developing robust
algorithms for a variety of computational problems.
3.6.1 Divide and Conquer
Divide and Conquer is a powerful algorithm design
technique that works by breaking a large problem
into smaller, more manageable parts. Each smaller
part is solved independently, and then their solutions
are combined to solve the original problem, as
shown in Figure 3.6. This approach is particularly
effective for problems that can be divided into similar
smaller problems, making it easier to find a solution
step by step.
78
Figure 3.6: Merge Sort Process
Example: Merge Sort is a classic example of a Divide and Conquer algorithm. The
algorithm begins by dividing an unsorted list into two halves. Each half is then sorted
independently, and finally, the two sorted halves are merged together to create the final
sorted list. Figure 3.6 illustrates the process of Merge Sort, showing how the list is
divided and then combined to produce a sorted output. This visualization highlights the
efficiency of the Divide and Conquer approach.
3.6.1 Greedy Algorithms
Greedy algorithms work by making a sequence of choices, each of which is locally
optimal, with the hope that these choices will lead to a globally optimal solution. The
greedy approach is often used when a problem has an optimal substructure, meaning
that the optimal solution to the problem can be constructed from optimal solutions to
its sub problems.
Example: A classic example of a greedy algorithm is the Coin Change problem. Suppose
you have coins of different denominations and you want to make a specific amount with
the fewest coins possible. The greedy algorithm would involve choosing the largest
denomination coin that does not exceed the remaining amount, then subtracting that
value and repeating the process until the desired amount is achieved.
Greedy algorithms are often faster and easier to implement than other techniques, but
they don't always guarantee the optimal solution for every problem. Always analyze the
problem to ensure that a greedy approach is appropriate.
3.6.1 Backtracking
Backtracking is a method used in solving problems where you build up a solution step by
step. If you find that a particular path doesn't lead to a solution, you simply go back and
try a different path. It's like trying out different routes on a map and turning back if you
find that you're going the wrong way. This method is often used for problems where you
need to look at all possible options, like with puzzles or problems that involve different
combinations.
3.7 Commonly Used Algorithms
Algorithms are essential tools in computer science and are applied to a wide range of
problems, from sorting data to searching for information in large datasets. Some
algorithms are foundational, serving as building blocks for more complex operations.
This section explores some of the most commonly used algorithms, including sorting,
searching, and graph traversal algorithms.
3.7.1 Sorting Algorithms
Sorting algorithms are used to arrange data in a particular order, such as ascending or
descending. Sorting is a fundamental operation that is often a prerequisite for other
tasks like searching and data analysis.
3.7.1.1 Bubble Sort
Bubble Sort is one of the simplest sorting algorithms. It works by repeatedly stepping
through the list, comparing adjacent elements, and swapping them if they are in the
wrong order. This process is repeated until the list is sorted.
Process:
• Start from the beginning of the list.
• Compare each pair of adjacent elements.
• Swap them if they are in the wrong order.
• Continue the process until no more swaps are needed.
Example: Consider the list [5,3,8,4,2]. Bubble Sort will compare 5 and 3, swap them, then
move to the next pair, and so on. After several passes through the list, the algorithm will
sort the list as [2,3,4,5,8].
Complexity: The time complexity of Bubble Sort is O(n2), making it inefficient for large
80
datasets. However, it is easy to understand and implement, making it useful for
educational purposes and small datasets.
While Bubble Sort is easy to implement, consider using more efficient sorting algorithms
like Quick Sort or Merge Sort for larger datasets to save time and resources.
Binary Search is only effective on sorted lists. If your data isn't sorted,
consider using a sorting algorithm like Merge Sort before applying
Binary Search!
82
3.7.3 Graph Algorithms
Graph algorithms are used to explore and analyze graphs, which are data structures
made up of nodes (vertices) connected by edges. These algorithms are essential for
network analysis, route planning, and social network analysis.
3.7.3.1 Breadth-First Search (BFS)
Breadth-First Search (BFS) is a graph traversal algorithm that explores all the nodes of a
graph level by level, starting from a given node (often called the root). It uses a queue to
keep track of the nodes that need to be explored.
Process:
• Start from the root node and enqueue it.
• Dequeue a node, process it, and enqueue all its unvisited neighbors.
• Repeat the process until the queue is empty.
Example: In a social network graph, where each node represents a person and edges
represent friendships, BFS can be used to find the shortest path between two people
(e.g., finding the degree of separation between two users).
Complexity: The time complexity of BFS is O(V + E), where V is the number of vertices
and E is the number of edges. This makes it efficient for exploring large graphs.
3.7.3.2 Depth-First Search (DFS)
Depth-First Search (DFS) is another graph traversal algorithm that explores as far down a
branch as possible before backtracking to explore other branches. It uses a stack to
manage the nodes to be explored.
Process:
• Start from the root node and push it onto the stack.
• Pop a node, process it, and push all its unvisited neighbors onto the stack.
• Repeat the process until the stack is empty.
Summary
This chapter offers a thorough introduction to algorithms and problem-solving. It
begins by defining and categorizing computational problems as solvable or unsolvable,
and tractable or intractable. Key algorithmic methods such as generate and test are
explained, alongside problem types like search, sorting, optimization, and decision
problems. It also explores design techniques including greedy algorithms, divide and
conquer, dynamic programming, and backtracking. The chapter further covers
commonly used algorithms, efficiency, and complexity analysis with Big O notation. It
highlights the importance of algorithmic thinking for effective problem-solving and
practical implementation, emphasizing the need to evaluate and balance trade-offs
based on specific problem requirements.
85
10. Which of the following algorithms has a time complexity of O(n log n)?
(a) Bubble Sort
(b) Binary Search
(c) Merge Sort
(d) Insertion Sort
Short Questions
1. Differentiate between well-defined and ill-defined problems within the realm of
computational problem-solving.
2. Outline the main steps involved in the Generate and Test algorithm.
3. Compare tractable and intractable problems in the context of computational
complexity.
4. Summarize the key idea behind Greedy Algorithms.
5. Discuss the advantages of using Dynamic Programming.
6. Compare the advantages of Breadth-First Search (BFS) with Depth-First Search (DFS)
in graph traversal.
7. Explain the importance of breaking down a problem into smaller components in
algorithmic thinking.
8. Identify the key factors used to evaluate the performance of an algorithm.
Long Questions
1. Discuss the different complexity classes (P, NP, NP-hard, NP-complete) and their
importance in understanding problem difficulty.
2. Provide a detailed explanation of why the Halting Problem is considered unsolvable
and its implications in computer science.
3. Discuss the characteristics of search problems and compare the efficiency of Linear
Search and Binary Search algorithm.
4. Discuss the nature of optimization problems and provide examples of their
applications in real-world scenarios.
5. Explain the Backtracking technique with reference to the N-Queens problem. Discuss
how the algorithm explores different configurations to solve the problem.
6. Explain the process and time complexity of the Bubble Sort algorithm. Compare it
with another sorting algorithm of your choice in terms of efficiency.
7. Discuss the differences between time complexity and space complexity. How do they
impact the choice of an algorithm for a specific problem?
86
UNIT
Computational Structures
4
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Define and explain the purpose of primitive computational structures, including
lists, stacks, queues, trees, and graphs.
· Identify and describe the characteristics and properties of different
computational structures.
· Perform basic operations such as insertion, deletion, traversal, and searching on
various computational structures.
· Understand and implement the LIFO (Last-In, First-Out) and FIFO (First-In, First-
Out) principles in stacks and queues, respectively.
· Compare and contrast different types of trees and graphs, and apply appropriate
operations to them.
· Analyze and choose the most suitable computational structure based on
problem requirements, data organization, and performance considerations.
· Apply computational structures in real-world scenarios, including data
organization, task scheduling, and network modeling.
· Combine different computational structures to solve complex problems and
enhance functionality.
87
Introduction
In this chapter, we will explore key computational structures, such as lists, stacks,
queues, trees, and graphs, which are fundamental in programming. We will examine
their properties, operations, and how to implement them efficiently. Additionally, we
will discuss selecting the appropriate structure based on specific problem requirements
and demonstrate their application in real-world scenarios. By the end of this chapter,
you will understand how to effectively use these structures in various contexts.
4.1 Primitive Computational Structures
In our daily lives, we often need to organize and manage data. For instance, think about
the way you store your contacts on your phone, keep a to-do list, or even stack plates in
your kitchen. Similarly, in the world of computers, we need to organize and manage
data. Computational structures help us do that.
4.1.1 Lists
A list is a data structure used to store multiple pieces of data in a specific sequence. Each
piece of data, known as an element, is positioned at a particular index within the list,
facilitating easy access and management.
4.1.1.1 List Creation
In Python, Lists are created using square brackets '[]', with each item separated by a
comma. Here's how you can create and work with a list in Python:
A type of list known as a linked list uses nodes, where each node
contains a value and a reference to the next node.
88
4.1.1.2 List Properties
List has following properties:
1. Dynamic Size A list in Python can change its size. You can add new items to the list
or remove items without any problem. The list will automatically adjust to fit the
changes.
2. Index-Based Access Every item in a list has a position, called an index. The first item
has an index of 0, the second item has an index of 1, and so on. You can use these
indexes to get specific items from the list.
3. Ordered Collection The order in which you add items to a list is preserved. This
means that if you add an item first, it will stay in that position unless you change it.
4. Heterogeneous Elements A list can hold different types of items together. For
example, you can have numbers, words, and even other lists all in one list.
5. Mutability Lists are changeable, meaning you can update, add, or remove items
from the list after you create it.
6. Supports Duplicates A list can contain the same item more than once. This means
you can repeat values in the list if needed.
# Example List
items = ["Decorations", "Snacks", "Cold drinks", "Plates" "Balloons"]
# Characteristics of Lists:
# Nature of the Data Structure
print("List of items:", items)
# Mutability
items.append("Party Hats")
items.remove("Snacks")
print("After modifications:", items)
# Homogeneous vs. Heterogeneous
print("Homogeneous List:", [1, 2, 3, 4])
print("Heterogeneous List:", ["Apple", 42, 3. 14, True] )
# Properties of Lists:
# Length
print("Number of items:", len(items))
# Indexing print("Item at index 2:", items [2])
# Ordering print("Order maintained:", items)
# Duplication
print("List with duplicates:", ["Decorations", "Snacks", "cold drinks", "Snacks"])
89
The code above shows different features of lists. First, it creates a list called 'items' with
party essentials, keeping the items in the order they were added. We then demonstrate
that lists can be changed by adding 'Party Hats' as a new item and removing 'Snacks',
which shows that lists are dynamic.
Did you know that lists in Python can be nested, meaning you can
have lists within lists? This feature is useful for representing complex
data structures.
# Output: [’’Invite friends’’, ‘’Buy cold drinks’’, ’’Buy decorations’’, ‘’Buy snacks’’,
“Order cake”]
c. Extending the List: You can also add multiple items at once using the 'extend()'
functions.
party_list = ["Invite friends", "Buy decorations ", "Buy snacks”, "Buy cold
drinks"]
party_list.extend(["Party hats", "Streamers"]) # Add multiple items at once
print(party_list)
# Output: [’’Invite friends’’, ’’Buy decorations’’, ‘’Buy snacks ‘’, ‘’Buy cold
drinks’’, ’’Party hats’’, ‘’Streamers’’]
90
2. Deletion: Removing an item from your list is like crossing off a task you've
completed. You can remove items in various ways
a. Removing by Value: Use the 'remove()' function to delete the first occurrence of
a specific item.
party_list = ["Invite friends ","Buy decorations”, "Buy snacks”, "Buy cold drinks"]
party_list.remove ("Buy snacks”) # Removes ’Buy snacks ’ from the list
print(party_list)
# Output: [’Invite friends’, ’Buy decorations’, ’Buy cold drinks ’]
party_list = ["Invite friends ", "Buy decorations", "Buy cold drinks " ]
party_list.pop (0) # Removes the item at index 0
print(party_list)
# Output: [’Buy decorations’, ’Buy cold drinks’]
c. Removing All Items: Use the 'clear()' function to remove all items from the list.
3. Searching: Finding an item in a list is similar to looking for a specific task in your to-do
list. You can search for an item using different functions:
a. Checking for Existence: Use the 'in' keyword to check if an item exists in the
list.
91
b. Finding the Index: Use the 'indexO' function to find the position of an item
in the list.
party_list = ["Invite friends", "Buy decorations", "Buy cold drinks " ]
index = party_list.index("Buy decorations") # Finds the position of ’Buy decorations’
print("Index of ’Buy decorations’:", index)
# Output: Index of ’Buy decorations’: 1
4.1.1.4 Applications of Lists
· Data Storage and Manipulation: Lists are commonly used to store and
manage collections of data, such as records, entries, or values. They allow for
easy insertion, deletion, and access to elements.
· Stack and Queue Implementations: Lists can be used to implement stack
(LIFO) and queue (FIFO) data structures, which are fundamental for various
algorithms and tasks in computing. Stacks and queues are discussed in
sections 4.1.2 and 4.1.4, respectively.
· Sorting and Searching Algorithms: Lists are frequently used in algorithms
for sorting and searching data. Algorithms like bubble sort, selection sort, and
binary search often operate on lists to arrange or find data efficiently.
· Function Arguments: Lists are often used to pass multiple arguments to
functions, enabling flexible and efficient handling of inputs in programming.
· Matrix Operations: Lists can be used to represent and manipulate matrices
in numerical and scientific computing, where each list represents a row or
column of the matrix.
4.1.2 Stacks
A stack is a simple data structure where you can only add or remove items from one end,
known as the “top”. Both insertion and deletion of elements occur at this top end. A stack
operates on the Last-In, First-Out (LIFO) principle, meaning that the most recently added
element is the first one to be removed.
4.1.2.1 Properties of Stack
· LIFO Principle: A stack works by the Last-In, First-Out rule. The last item
added is the first one removed.
· Single Access Point: You can only add or remove items from the top of the
stack.
· Order Preservation: The order in which you add items is preserved, with the
last item added being the first to leave.
· Size Flexibility: A stack can either have a fixed size or grow as needed.
Sequential Access: You can only access items in the order they were added, starting
from the top.
92
Figure 4.2: Stack of Books
93
The code creates an empty stack to hold books. It then adds three books (“Book A”,
“Book B”, and “Book C”) one by one to the top of the stack. Finally, it removes the top
book “Book C” from the stack, showing how the last book added is the first one taken off.
Did you know that stacks are used in algorithms like depth-first search
(DFS) in graph traversal? They help manage the nodes to be explored
in a LIFO manner.
95
4.1.3.3 Function Call Management:
Stacks are very useful in managing function calls in programming. Let's break it down
with a simple example: Imagine you are making a series of phone calls. Each time you call
someone, you write their name on a notepad. When you finish talking, you cross off their
name.
How This Works:
1. Making a Call: When you make a call, you write down the name on top of
the notepad. This is like pushing information onto the stack.
2. Ending a Call: After you finish talking, you cross off the name. This is like
popping information off the stack.
In programming, when a function is called, its details (like what it needs to do and where
to return after it's done) are written on the stack. This helps the computer remember
what to do next. When the function finishes, it removes (or pops) its details from the
stack, just like crossing off the name.
4.1.3.4 Balancing Parentheses:
When dealing with infix expressions, parentheses are used to show which operations
should be done first. Balancing parentheses is important to ensure that every opening
parenthesis has a matching closing parenthesis.
Steps to Check Parentheses:
1. Use a stack to keep track of opening parentheses.
2. When you find an opening parenthesis (, push it onto the stack.
3. When you find a closing parenthesis ), pop the top of the stack.
4. If the stack is empty after processing all parentheses, they are balanced.
5. If the stack is not empty, or if you try to pop from an empty stack, the
parentheses are not balanced.
Example: For the expression (3 + 4) * (5 - 2), the parentheses are balanced. Each (
has a matching ).
4.1.3.5 Undo Mechanism:
Stacks are used to implement undo functionality in applications such as Not Pad and
Microsoft Word. Each action you perform is saved on a stack. When you want to undo an
action, the most recent action is removed from the stack and reversed. This allows you to
go back to the previous state.
Example:
Imagine you are using a text editor and you make several changes to a document, like
typing new text or deleting old text. Here's how the undo mechanism works:
1. Performing Actions: As you make changes, each action (such as typing or
deleting text) is saved on a stack. For example, if you type “Hello”, this action is
96
pushed onto the stack.
2. Undoing an Action: When you press the undo button, the most recent action
(like typing “Hello”) is removed from the stack. The text editor then reverses this
action (e.g., it deletes “Hello” from the document).
3. Multiple Undos: If you continue to press undo, each previous action is reversed
in the order they were performed. If you typed “World” after “Hello”, pressing
undo would first remove “World”, then “Hello”.
Class Activity
Consider the task of managing a stack of plates in a restaurant kitchen. Write a
python code to simulate the operations of adding and removing plates from
this stack.
Requirements:
1. Create a Stack Class:
· Define a Stack class using a list to represent the stack of plates.
· Implement methods for push (to add a plate), pop (to remove
a plate), and peek (to view the top plate without removing it).
2. Demonstrate Stack Operations:
· Push the following plates onto the stack: Plate 1, Plate 2, Plate
3.
· Display the stack after each addition.
· Pop a plate from the stack, and print both the removed plate
and stack.
· Peek at the top plate and print its value.
4.1.4 Queues
A queue is like a line in front of the a bank
or a ticket counter. The first person to get
in line is the first person to be served. In a
computer, a queue works the same way. It
keeps track of things so that the first item
added is the first one to be taken out. Just
like in a bank line, you add things to the
back and remove them from the front,
following the FIFO (First-In, First-Out)
principle, as shown in Figure 4.3.
97
4.1.4.1 Properties of Queue
Below are the key properties of a queue.
· Order Preservation: A queue keeps track of the order of items. The first item
you put in the queue is the first one to come out.
· FIFO Principle: A queue works on the “First-In, First-Out” rule. This means the
first item added to the queue is the first one to be removed.
· Dynamic Size: A queue can grow or shrink in size as you add or remove
items. It adjusts automatically based on the number of items it holds.
4.1.4.2 Queue Operations
Queues support two primary operations:
· Enqueue (Add an Item): This is like adding a person to the end of the line. In a
queue, you add items to the back.
· Dequeue (Remove an Item): This is like serving the person at the front of the
line. In a queue, you take items out from the front.
· Additional operations might include checking if the queue is empty, retrieving
the element at the front without removing it, and determining the size of the
queue.
# Built-in module to implement queues in python
from queue import Queue
# Create a new queue
q = Queue ()
# Add people to the queue (Enqueue)
q. put (" Ahmed") # Adds Ahmed to the end of the queue
q.put ("Fatima") # Adds Fatima to the end of the queue
q.put ("Ali") # Adds Ali to the end of the queue
# View the person at the front of the queue (Peek)
front_person = q. queue [0] # Looks at the person at the front without
removing them
print(front_person) #Remove a person from the front of the queue
(Dequeue)
removed_person = q.getO # Removes and returns the person at the front
of the queue
print(removed_person)
# Add another person to the queue (Enqueue)
q.put("Sara") # Adds Sara to the end of the queue
# View the updated queue updated_queue = list(q.queue)
print(updated_queue)
98
The code manages a line of people using a queue. It adds people to the end of the line,
checks who is at the front without removing them, and then serves (removes) the person
at the front. Finally, it adds another person to the end and shows the updated line.
The 'peek' operation allows you to view the element at the front of the queue without
removing it. It's similar to looking at the first book on the shelf to see which one will be
picked next.
101
· Order of Printing: The queue ensures that documents are printed sequentially,
based on the order they were submitted. The document that was sent first will be
printed first, while subsequent documents will wait their turn in the queue.
· Advantages of Using a Queue: By employing a queue, print spooling prevents
issues such as documents being printed out of sequence or confusion arising
from simultaneous print requests. This orderly approach allows the printer to
handle multiple tasks efficiently and fairly, maintaining an organized process.
4.1.5.5 Data Buffering
Queues play a crucial role in buffering data streams, which helps manage and process
data efficiently. To understand this concept better, let's look at a couple of real-world
examples.
1. Online Video Streaming: When you watch a video online, the video is not
played all at once. Instead, it is buffered in small chunks. This means that as
the video plays, a queue
stores and loads parts of the video ahead of what you are currently watching.
This buffering queue helps ensure that the video plays smoothly without
interruptions, even if there are delays in data transfer from the internet.
2. Printer Queue: Imagine you have several documents to print, but your
printer can only handle one document at a time. When you send multiple
print jobs to the printer, they are placed in a queue. The printer then
processes each document in the order they were received. This queue helps
manage and organize the print jobs so that each document is printed one
after the other without confusion.
4.1.6 Trees
A tree data structure organizes information in a way that spreads out from a main point
called the root node. In a tree, each piece of information, called a node, can connect to
other pieces, which are also nodes, forming a branching structure. This branching
structure is different from a list, where items are organized one after the other in a
straight line.
Example: In a family tree, the oldest ancestors represent the root node, serving as the
starting point of the hierarchy. Each individual in the tree may have descendants,
forming subsequent levels of the hierarchy, as illustrated in Figure 4.5. This hierarchical
structure is not suitable for storage in a linear format, such as a list, due to the complex
parent-child relationships. Therefore, a tree data structure is employed to efficiently
store and access such hierarchical data, enabling clear representation and retrieval of
information.
102
Figure 4.5: Family Tree
Certainly! Here's a simplified version focusing on the core properties of trees, using
layman friendly language:
Here's a simple example of how to create a family tree structure in Python using classes.
This implementation shows how to create family members (nodes) and how to add
children (descendants) to them.
103
class Fami1yMember :
def _ _init_ _ (self , name): self.name = name self.children = []
class FamilyTre e:
def _ _init_ _ (self , an c e s t o r _ n am e ) :
self.root = Fami1yMember(ancestor_name)
def add_child(self , parent_name , ctii 1 d_name ) :
parent_node = self._find_member(self.root, parent_name
if parent_node:
parent_node.children.append(FamilyMember( child_name))
def _find_member (self , current.member, name):
if current.member.name == name:
return current.member
for child in current_member.children:
result = self._find_member(child, name)
if result :
return result
return None
• Example usage
family_tree = FamilyTree (’Grandparent ’)
family_tree.add_child(’Grandparent’ , ’Parenti’)
family_tree.add_child(’Grandparent’, ’Parent2’) family_tree.add_child(’Parenti’,
’Childl’) family_tree.add_child(’Parenti’, ’Child2’)
(commonly 1). Balanced trees are essential for efficient operations such as searching,
insertion, and deletion, as they keep these operations close to O(log n) time complexity.
Example: Organizing Books in a Library
Consider a library that needs to efficiently organize and locate books on shelves. If the
books were simply arranged in a linear order on a single shelf, finding a specific book
might require scanning through many books. Instead, imagine the books are organized
using a balanced tree structure.
At the root of this tree, we have a central category, such as Science. This category could
then be divided into subcategories like Physics and Biology, each forming the children
of the root. Within each subcategory, further divisions can be made, such as separating
Physics into Classical Mechanics and Quantum Physics, and Biology into Botany and
Zoology. This process continues, ensuring that no single branch of the tree becomes
significantly longer than the others.
105
In this balanced tree, searching for a book on Quantum Physics involves traversing
down the branches of the tree: first to Science, then to Physics, and finally to Quantum
Physics. The balanced nature of the tree ensures that this search is quick, as the tree's
height remains logarithmic relative to the number of categories, avoiding lengthy
search times.
This concept is illustrated in Figure 4.7 while the computer science tree has upside down
as shown in Figure 4.8.
4.1.7.1 Operations on Tree
In a tree structure, there are some basic operations that help us manage and work with
the data. Let's break them down:
· Insertion: Imagine you're adding a new family member to your family tree.
Insertion is like finding the right spot in the tree and adding the new member
there. We connect the new person to their parent in the tree, making sure they
are part of the family structure.
Here's how you can insert a new member into the Family Tree:
· Deletion: Sometimes, we need to remove a member from the tree. Deletion is
the process of taking someone out of the family tree. We carefully remove them,
making sure the rest of the tree still makes sense and stays connected.
· Traversal: Tree traversal like walking through the family tree to visit each
member. There are different ways to do this, like starting from the top and
visiting each person one by one, or visiting all the children of a person before
moving to the next branch. There are three common types of tree traversals are
there: In-order, Pre-order, and Post-order. We will use the following simple tree
structure with numeric data to understand traversal functions more easily.
108
2. AVL Trees:
An AVL tree is a type of binary tree that keeps itself balanced, meaning the height of the
tree is managed carefully. If one side of the tree starts getting too tall compared to the
other, the tree rearranges itself to maintain balance.
Example: Imagine you are organizing books on shelves. You want to make sure that the
shelves are balanced, so one side isn't heavier than the other. This is similar to an AVL
tree as shown in Figure 4.10.
112
· Weighted Graphs: In a weighted graph, each edge has a weight or cost
associated with it. This weight represents the distance, time, or cost required
to travel from one vertex to another as shown in Figure 4.11.
Example: Imagine a map of a city where each road has a different distance or
travel time. If you want to travel from one landmark to another, the map
provides the distance or travel time for each road. This information helps you
determine the shortest or quickest route between landmarks.
Graph Implementation Using Python
Graphs can be implemented in Python using libraries such as NetworkX. Here's a basic
example:
import networkx as nx
import matplotlib.pyplot as pit
# Create a graph object
G = nx.Graph()
# Add vertices (nodes)
G . add_node( ’ A ’ )
G.add_node( ’B ’ )
G . add_node( ’ C ’)
# Add edges (links) between vertices
G. add_edge(’A’ , ’B ’)
G . add_edge(’B ’, ’ C ’)
# Draw the graph
nx.draw(G , with_labels=True)
pit.show ()
Summary
This chapter offers a comprehensive overview of fundamental computational structures,
including lists, stacks, queues, trees, and graphs. It details their properties, operations,
and applications, emphasizing their roles in organizing and managing data. The chapter
also addresses the criteria for selecting appropriate data structures based on problem
requirements. Additionally, it explores the integration of different computational
structures to address complex problems effectively. By providing a detailed
understanding of these structures, the chapter aims to enhance the reader's ability to
apply them effectively in various computational contexts.
119
4. When converting an infix expression to postfix notation, what does a stack
help to manage?
a) Order of operands
b) Priority of operators
c) Parentheses
d) Both b and c
5. Which operation is used to add an item to a queue?
a) Dequeue
b) Peek
c) Enqueue
d) Remove
6. In the context of Breadth-First Search (BFS) in a tree, which operation of queue
is used to visit nodes level by level?
a) Adding nodes to the end of a stack.
b) Removing nodes from the end of a list.
c) Enqueueing nodes to a queue.
d) Dequeueing nodes from a stack.
7. Which of the following tree traversals visits the root node before its children?
a) In-order
b) Pre-order
c) Post-order
d) Level-order
8. Which of the following is true about the height of a tree?
a) The height is the number of edges from the root to the deepest node
b) The height is the number of nodes from the root to the deepest node
c) The height is the number of children of the root node
d) The height is always equal to the number of nodes in the tree
9. Which graph traversal explores all immediate neighbors of a vertex before moving
to the next level?
a) Depth-First Search (DFS)
b) Breadth-First Search (BFS)
c) Depth-Limited Search (DLS)
d) Iterative Deepening Search (IDS)
10. For which scenario would a graph data structure be most appropriate?
a) Managing a to-do list
b) Modeling a line of customers in a store
c) Representing connections in a social network
120
Short Questions
1. Explain how the ' extend() ' function works in python lists. Provide an example.
2. Explain the potential issues which could arise when two variables reference the
same list in a program? Provide an example.
3. Define a stack and explain the Last-In, First-Out (LIFO) principle.
4. How does the stack help in balancing parentheses in an expression? Describe
the process.
5. Differentiate between the Enqueue and Dequeue operations of queue.
6. Explain how the concept of a queue is applied in a computer's job scheduling
system?
7. How can lists be utilized to implement other data structures?
8. Differentiate between the Depth-First Search (DFS) and Breadth-First Search
(BFS).
Long Questions
1. Discuss the dynamic size property of lists in Python. How does this property
make lists more flexible?
2. Write a python program to manage a project's task list. Start with an initial list
containing the following tasks=[design, development, testing, deployment].
Perform the following operations on the tasks list:
· Add 'review' to the end of the list.
· Insert 'planning' at the third position in the list.
· Update 'testing' to quality assurance.
· Remove 'development ' from the list by its value.
· Remove the task at index 1 from the list.
· Find the index of the task 'deployment ' and print it.
· Print the final list after all modifications.
· Count and print the number of tasks in the list.
3. Discuss two real-world situations where stacks are commonly used.
Explain how stack operations function in these contexts.
4. Consider the following infix expression (5 + 2) * (3 - 1).
(a) Describe the step-by-step process to convert this infix expression
into postfix notation using a stack.
(b) Illustrate the state of the stack and the output list after processing
each token of the infix expression.
Hint: A token is a single element in an expression, such as a number,
operator, or parenthesis.
5. Write a Python code to simulate a queue of print jobs. The code perform
121
following operations:
(a) Create an empty queue.
(b) Add three print jobs to the queue.
(c) Display the print job at the front of the queue without removing it.
(d) Remove the print job from the front of the queue.
(e) Add another print job to the queue.
(f) Display the updated queue of print jobs.
6. Explain the different types of tree traversals (In-order, Pre-order, Post-order).
Provide an example of each traversal using a given tree structure, and explain
how each traversal method processes the nodes.
Consider the following graph and perform the operations specified below:
Required Operations:
(a) Start from node A, write down the sequence of nodes visited during a
depth-first search traversal of the graph.
(b) Start from node A, write down the sequence of nodes visited
throughout a breadth-first search traversal of the graph.
8. Consider the task of organizing a desk. Describe how you can use both a stack
and a queue to manage tasks such as sorting papers, putting away books, and
cleaning the desk.
122
UNIT
Data Analytics
5
Student Learning Outcomes
By the end of this chapter, students will be able to:
· understand the role and importance of model building and their real world
applications
· build basic statistical models for real world problems and test their performance
· understand and explain experimental design in data science
· explain the types, uses, methods of data visualizations,
· understand the benefits of visualizing data through descriptive statistics
· explain and create a data visualization using data visualization software (for
example MS Excel, Google Sheets, Python, Tableau, or Matplotlib).
123
Introduction
Model building is the process of creating simplified representations of complex
problems. It helps in understanding, analyzing, and solving real-world issues by
focusing on key elements.
5.1 Model Building
5.1.1 Definition and Importance of Models
In simple terms, a model is a simplified way of looking at a complex problem or situation.
It helps to understand, explain, or predict how things work. Just like a map helps
someone navigate a city by showing roads and landmarks, a model helps us understand
a problem by focusing on the most important parts and leaving out unnecessary details.
Example: Consider a student preparing for exams. To decide how much time to spend on
each subject, the student creates a study plan. This plan is a model that simplifies their
schedule by focusing on important subjects and ignoring less relevant tasks.
5.1.2 Role of Models in Decision-Making
Models are useful because they give a structured way to think about a problem. They
take complicated information and make it easier to work with. This is especially
important in decision making, where models help us consider different outcomes
before making a choice.
Example: When a farmer use a model to decide the best time to plant crops. By studying
weather patterns and soil conditions, the model helps the farmer predict the right
planting time, which increases the chances of a good harvest.
Where: - xi represents each individual value in the data set, - µ is the mean of the data set,
- N is the total number of values in the data set.
Calculating Standard Deviation:
Class A:
Standard 12.56 Deviation = 3.55
127
Class B:
Standard 456 Deviation = 21.26
The standard deviation for Class A is approximately 3.55, while for Class B, it is about
21.26. This means that Class A's scores are closely packed around the mean, whereas
Class B's scores are more widely scattered. The standard deviation helps us easily
understand how much variation there is in the scores.
5.2.4 Introduction to Probability
Probability is the study of how likely an event is to happen. It helps us predict outcomes
based on what we know.
Example: Consider flipping a coin. There are two possible outcomes: heads or tails. Since
both outcomes are equally likely, the probability of getting heads is 50% (or 1/2), and the
probability of getting tails is also 50%.
We can express this mathematically as:
Here, the number of customers is our independent variable (X), and the daily earnings
are the dependent variable (Y ).
· Step 2: Understanding the Linear Regression Formula
The formula for simple linear regression is:
Y =β0+β1x+ϵ
Where:
– Y is the dependent variable (in our case, daily earnings),
– X is the independent variable (the number of customers),
– β0 is the intercept, which is the starting value of Y when X = 0,
133
– β1 is the slope, which shows how much Y changes with each unit
increase in X,
– ε is the error term, which accounts for the difference between the
predicted and actual values.
· Step 3: Building the Linear Regression Model
When building a linear regression model, our goal is to find the best line that
explains how two things are related in this case, the number of customers and
daily earnings. Here's how we get the values for the slope (40) and intercept
(300):
Understanding the Slope (β1 = 40)
The slope shows how much extra money we make for every new customer. Let's
use our data to figure it out:
If you notice, for every 5 extra customers, earnings go up by 200 rupees. So, for each new
customer:
β1 = 200/ 5 = 40
This means every new customer adds 40 rupees to our earnings.
Understanding the Intercept (β0 = 300)
The intercept (β0) represents the earnings when no customers visit. To find this value, we
look at where the line crosses the vertical axis when the number of customers is zero. In
simpler terms, it tells us what the base earnings are, even if no one shows up.
Let's look at the data:
134
Using this data, we calculate the slope (β1 = 40) means for every additional customer,
earnings increase by 40 rupees. Now, to find the intercept, we need to consider how
much we earn when there are no customers.
We can use the equation:
Earnings = β0 + β1 × Customers
If we take any data point, say when there are 10 customers, the earnings are 500 rupees.
Substituting these values into the equation:
500 = β0 + (40 × 10)
500 = β0 + 400
Solving this gives:
β0 = 500 − 400 = 100
This means that, based on the data, if no customers show up, you'd still expect to make
100 rupees, maybe from regular customers or other fixed earnings. So, the intercept
value of 100 rupees represents the minimum amount you'd make on a day with zero
customers.
· Final Equation:
Earnings = 100 + 40 x Customers
This equation means:
– You'll always earn 100 rupees, even if no one comes.
– Each new customer adds 40 rupees to your total.
· Step 4: Interpreting the Model
Once the model is built, we can use it to predict future earnings. For example, if
you expect 22 customers tomorrow, the predicted earnings would be:
Here, β0 = 1 and β1 = 0.6. This means that for each hour studied, the
likelihood of passing
the exam increases. If a student studies for 5 hours, we can calculate their
passing probability:
P(Pass) = 1 1 + e−(1+0.6×5) ≈ 0.83This means there is an 83% chance that
the student will pass after studying for 5 hours.
· Testing the Model:
Once the model is built, we can use it to make predictions. Let's say a new
student studies for 4 hours. We can use our model to find the probability of
passing:
137
Student Math Score English Score
Basim 85 70
Umer 90 65
Anie 50 80
Tallat 40 85
Maliha 60 60
We can use clustering to group these students based on their performance in these two
subjects. K-means Clustering
K-means clustering is one of the simplest and most popular techniques to group data. In
K-means, we need to decide how many groups (clusters) we want. For this example, let's
say we want to divide the students into two clusters: one for students who are strong in
math and one for students who are strong in English. The algorithm will group students
with similar performance in math and English together by calculating the distance
between their scores and finding patterns. It will assign students like Basim and Umer
(who are good at math) to one group and students like Anie and Tallat (who are good at
English) to another group.
Step-by-step Working of K-means:
138
After calculating these distances, we assign each student to the nearest center.
Based on the calculations:
1. Basim and Umer are closer to Center 1 (Basim), so they join Cluster 1 (Math-
strong).
2. Anie, Tallat, and Maliha are closer to Center 2 (Tallat), so they join Cluster 2
(English-strong).
· Step 4: Recalculate the centers.
Now that the students have been assigned to clusters, we need to recalculate the
centers by finding the average position (average scores) of the students in each
cluster.
139
· Step 5: Repeat steps 3 and 4 until the centers stop moving.
Now that the centers are updated, we will again calculate the distance between
each student and the new centers and reassign them if needed. This process
continues until the centers no longer change, which means the clusters are
stable.
For this example, after recalculating, the cluster centers are already quite stable.
Basim and Umer still be closer to the math-strong cluster, and Anie, Tallat, and
maliha would remain in the English-strong cluster.
After these steps, we will get two clusters: Cluster 1: Basim, Umer, and Maliha
(good in math) Cluster: 2 Anie and Tallat (good in English)
5.4.2 Evaluating and Interpreting Models
Once a model is built, it is important to check how well it performs and to
understand the results it provides. This is called model evaluation.
5.4.2.1 Performance Metrics
Performance metrics help us measure how well a model is doing. Some common metrics
include:
• Error Metrics
Error metrics measure how much the model's predictions differ from the actual
values. In our grocery example, if the model predicts a monthly grocery bill of
8,000 rupees but the actual bill is 10,000 rupees, the difference is the error.
• Accuracy Metrics
Accuracy metrics tell us how many of the model's predictions were correct. For
example, if a model predicts whether a student will pass or fail an exam, accuracy
measures how often the model was right.
5.4.2.2 Interpreting Outputs
Interpreting a model's output means understanding what the results tell us.
· Drawing Conclusions from Insights
For example, if our linear regression model shows that hours studied strongly
affect exam scores, we can conclude that students should study more hours to
improve their scores.
5.4.2.3 Ethical Considerations
When building models, it is important to consider the ethical implications, such as
fairness and privacy.
· Fairness and Bias
A model should be fair and not biased. For example, if a model is used to decide
who gets a loan, it should not unfairly favor one group of people over another.
· Data Privacy
When using personal data to build models, it is important to respect privacy. For
140
example, if a company is using customer data to build models, they should
ensure the data is secure and not shared without permission.
Always visualize your data before building models and test your results on new data for
better accuracy.
Class Activity
Linear Regression
You are given the following data that shows the relationship between the
number of hours studied and the marks obtained in a test by students. Your
task is to build a linear regression model that predicts the marks based on the
number of hours studied.
Hours Marks Obtained
1
Studied 20
2 25
3 35
4 40
5 45
6 50
Steps:
1. Plot the data points on a graph (Hours studied on the x-axis and Marks
obtained on the y-axis).
2. Calculate the equation of the line using linear regression.
3. Use the equation to predict the marks for a student who studied for 7
hours.
4. How well does the model fit the data? Justify your answer by calculating
the error between actual and predicted marks.
Class Activity
Logistic Regression
You are a college administrator, and you want to predict whether students will
pass or fail a final exam based on their midterm marks. The following data
shows the midterm marks of students and whether they passed or failed the
final exam. Your task is to build a logistic regression model to predict the
likelihood of passing based on midterm marks.
141
Class Activity
Midterm Marks Pass (1) / Fail (0)
30 0
40 0
50 0
60 1
70 1
80 1
90 1
Steps:
1. Plot the data points (Midterm marks on the x-axis, and Pass/Fail on
the y-axis).
2. Fit a logistic regression model to the data.
3. Based on the model, predict the probability of passing for a student
who scored 55 in the midterm.
4. Discuss how the logistic regression model helps in making this
prediction and whether it's accurate.
Class Activity
K-Means Clustering
You work in a local retail shop, and you want to segment your customers into
two groups based on their monthly spending in two categories: groceries and
clothing. The following table shows the monthly spending of six customers.
Your task is to use K-means clustering to group these customers into two
clusters based on their spending habits.
Customer Groceries Spending (in Clothing Spending (in $)
Customer 1 150
$) 100
Customer 2 200 150
Customer 3 100 50
Customer 4 80 20
Customer 5 160 90
Customer 6 40 10
Steps:
1. Choose K = 2 clusters and randomly select two initial cluster centers.
2. Assign each customer to the nearest cluster based on their spending.
3. Recalculate the cluster centers by finding the average spending in each
category for each cluster.
4. Repeat the process until the cluster centers stabilize.
5. Analyze the clusters and describe the spending habits of customers in
each group.
142
5.4 Introduction to Data Visualization
Data visualization is the process of representing data in a visual format, such as graphs or charts.
It helps us to quickly grasp patterns, trends, and insights from data.
5.5.1 Types of Visualizations
Data visualization is a powerful way to understand complex information. Different types of
visualizations serve various purposes, making it easier to interpret and analyze data. Below are
some common types of visualizations explained in detail:
5.5.1.1 Bar Charts
Bar charts are ideal for comparing different categories. Each bar represents a category, and the
height (or length) of the bar indicates the value associated with that category.
Example: Imagine you want to compare the sales figures for different products in a store. A
bar chart can visually represent this data.
Sales on Day 1 and Day 2 for various items
5.5.1.4 Scatterplots
Scatterplots display relationships between two variables. Each point represents an
observation, and the position on the graph indicates values for both variables.
Example: A scatterplot can be used to explore the relationship between the number of
hours studied and exam scores.
Hours
Figure 5.7: Scatterplot showing the relationship between hours studied and exam scores
144
5.5.1.5 Boxplots
Boxplots, or whisker plots, summarize data distribution by displaying the median,
quartiles, and potential outliers. They provide a visual summary of data variability.
Example: A boxplot can be used to compare the exam scores of different classes to see
which class performed better overall.
Summary
This unit focuses on model building and data visualization, equipping learners with
the skills to analyze, interpret, and present data effectively. Key topics include:
1. Model Building:
o Understand the role and importance of statistical models in solving real-
world problems.
o Learn to build basic statistical models (e.g., linear regression) and evaluate
their performance using appropriate metrics.
2. Experimental Design:
o Gain an understanding of experimental design in data science, including
hypothesis testing, control groups, and randomization.
3. Data Visualization:
o Explore the types and uses of data visualizations (e.g., bar charts, scatter
plots, heatmaps).
146
o Learn methods for creating effective visualizations to communicate insights
clearly.
4. Descriptive Statistics:
o Understand the benefits of visualizing data through descriptive statistics
(e.g., mean, median, standard deviation) to summarize and interpret data
trends.
5. Tools for Visualization:
o Develop hands-on skills in creating visualizations using tools like MS Excel,
Google Sheets, Python (Matplotlib), and Tableau.
147
b) The change in the dependent variable for a unit change in the independent
variable
c) The error term
d) The mean of the data
6. Which of the following is an example of a real-world application of statistical
models?
a) Predicting house prices
b) Creating social media posts
c) Designing websites
d) Writing essays
7. Which of the following is NOT a benefit of data visualization?
a) Identifying trends and patterns
b) Communicating insights effectively
c) Making data more complex
d) Summarizing large datasets
8. What is the primary goal of K-Means Clustering?
a) To classify data into predefined categories
b) To group data into clusters based on similarity
c) To predict continuous outcomes
d) To reduce the dimensionality of data
9. In K-Means Clustering, what does the "K" represent?
a) The number of features in the dataset
b) The number of clusters to be formed
c) The number of iterations required for convergence
d) The number of data points in the dataset
Short Questions
1. What is the importance of building statistical models in real-world
applications?
2. Name one basic statistical model used for predicting outcomes and explain
its purpose.
3. List two types of data visualizations and describe when you would use each.
4. How does visualizing data help in understanding descriptive statistics?
5. What is the purpose of using tools like MS Excel for data visualization?
6. Give an example of a real-world problem where a statistical model could be
applied.
148
Long Questions
1. Explain the role and importance of statistical models in solving real-world
problems.
2. Describe the steps involved in building a basic statistical model (e.g., linear
regression). Include details on data collection, model training, and evaluation.
3. Discuss the types of data visualizations and their uses.
4. Explain the concept of model evaluation in statistical modeling.
5. Explain the K-Means Clustering algorithm step by step. Include details on how
initial centroids are selected, how data points are assigned to clusters, and how
centroids are updated.
6. Describe a real-world scenario where K-Means Clustering can be applied.
Explain how you would preprocess the data, choose the value of K, and interpret
the results.
149
UNIT
Emerging Technologies
6
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Understand the basic concepts of cloud computing, including virtualization, scalability,
and on-demand access.
· Identify and explain the different types of cloud services: Infrastructure as a Service
(laaS), Platform as a Service (PaaS), and Software as a Service (SaaS).
· Describe various cloud deployment models, such as public, private, hybrid, and multi-
cloud, and compare their features.
· Recognize the core principles of blockchain technology and the role of peer-to-peer
networks in its functioning.
· Explain the applications of blockchain in real-world scenarios, including
cryptocurrencies, smart contracts, and product tracking.
· Discuss the implications of cloud computing and blockchain, especially in areas like
data security and resource management.
· Explore future trends and innovations in cloud computing and blockchain, including
edge computing and Blockchain 2.0.
150
Introduction
In the rapidly evolving landscape of technology, new paradigms and innovations are
continuously reshaping the way we interact with the digital world. This chapter explores
two of the most transformative technologies of our time: Cloud Computing and
Blockchain.
We begin by exploring the fundamentals of Cloud Computing, including its core
concepts such as virtualization, scalability, and on-demand access. We will also examine
the various types of cloud services like Infrastructure as a Service (laaS), Platform as a
Service (PaaS), and Software as a Service (SaaS), as well as different cloud deployment
models including public, private, hybrid, and multi-cloud environments. Understanding
these foundational elements will provide insights into the practical applications and
implications of cloud computing in various industries.
Following this, we shift our focus to Blockchain Technology, starting with its basic princi-
ples and components, such as the peer-to-peer network that forms the backbone of
blockchain's decentralized architecture. We will explore the use cases of blockchain,
including its role in cryptocurrencies and smart contracts, and discuss the applications
and implications of blockchain in areas like product tracking, financial services, and data
security.
The chapter concludes with a look into future trends and innovations within these
technologies, including edge computing, serverless architectures, and the next
generation of blockchain, often referred to as Blockchain 2.0 and beyond.
6.1 Definition and Overview of Emerging Technologies
Emerging technologies are new tools, systems, and methods that are currently being
developed or have just started to be used. These technologies have the potential to
change the way we live, work, and interact with the world. Here are some of the key
emerging technologies:
· Artificial Intelligence (AI): AI refers to machines and software that can think and
learn like humans. AI can help with tasks like recognizing faces, understanding
speech, and making decisions. It's used in everything from smart assistants like Siri to
self-driving cars.
· Cloud Computing: Cloud computing allows people to store and access data and
applications over the internet instead of on a local computer or server. This makes it
easier to share information, collaborate on projects, and scale up services without
needing expensive hardware. Examples include services like Google Drive, Dropbox,
and Amazon Web Services (AWS).
· Blockchain: Blockchain is a secure way to record and share information across many
computers, making it almost impossible to change or hack. It's best known for being
the technology behind cryptocurrencies like Bitcoin, but it's also used in other areas
151
like supply chains and contracts.
· Internet of Things (loT): loT connects everyday objects, like refrigerators, cars, and
even clothes, to the internet. This allows them to send and receive data, making our
lives more convenient. For example, a smart thermostat can learn your schedule and
adjust the temperature in your home automatically.
· Augmented Reality (AR) and Virtual Reality (VR): AR adds digital elements to the
real world using devices like smartphones or glasses. VR creates a completely virtual
environment that you can interact with using special equipment. These technologies
are used in gaming, education, and training.
· 5G Technology: 5G is the next generation of wireless technology, offering much
faster internet speeds and more reliable connections. This will enable better
performance for mobile phones, smart devices, and even new technologies like
augmented reality (AR) and virtual reality (VR).
· Quantum Computing: Quantum computers use the principles of quantum physics
to process information much faster than traditional computers. They have the
potential to solve very complex problems that are currently impossible for regular
computers to handle.
· Biotechnology: Biotechnology involves using living organisms, like bacteria and
plants, to create new products or solve problems. For example, scientists are using
biotechnology to develop new medicines, improve crops, and even create
environmentally friendly materials.
6.2 Cloud Computing
Cloud computing is a model that allows easy and convenient access to computing
resources like servers, storage, and applications over the internet. These resources can
be quickly provided and released with minimal management effort or service provider
interaction. Cloud computing is like having a powerful computer that you can access
over the internet. Instead of buying and maintaining your own expensive computers and
storage devices, you can use cloud services to store data, run applications, and manage
your computing needs. This makes it easier and cheaper to get things done, as you can
use as much or as little of the service as you need, and you only pay for what you use. It's
like renting a supercomputer that you can use whenever you need it, from anywhere in
the world.
6.2.1 Basic Concepts of Cloud Computing
Cloud computing encompasses several basic concepts that are foundational to its
functionality and benefits.
6.2.1.1 Virtualization
Virtualization is a technology that allows a single physical machine to run multiple
virtual machines. It is like having a magic trick that lets one physical computer act like
152
many separate computers. Imagine you have a single powerful computer, but with
virtualization, you can create several “virtual” computers inside it. Each of these virtual
computers can run its own operating system and applications as if they were
independent machines. This helps make better use of the hardware, reduces costs, and
allows for easier management and flexibility.
It's like turning one computer into many, making it possible to do more with less.
6.2.1.2 Scalability and Elasticity
Scalability and elasticity are important concepts in cloud computing that help manage
resources efficiently.
Scalability means you can add more resources when you need them. For example,
imagine you run an online store that usually has a steady number of visitors. However,
during busy times like Eid or 14th August sales, you get a huge spike in traffic. With
scalability, you can add more servers to handle this increased traffic, ensuring your
website runs smoothly without slowing down or crashing.
Elasticity takes this a step further by allowing the system to automatically adjust
resources based on the current demand. For instance, using the same online store
example, if your website starts getting a lot of traffic, the cloud service can automatically
add more servers to handle the load. When the traffic decreases after the sale, the
system can reduce the number of servers, so you're not paying for resources you don't
need. This automatic adjustment helps keep your website running efficiently and cost-
effectively.
6.2.1.3 On-Demand Access
On-demand access means that you can use computing resources whenever you need
them, without waiting for a long setup process. This is like being able to turn on a tap to
get water whenever you want, instead of having to dig a well first.
Example: Imagine you are working on a school project and suddenly need extra storage
space to save your files. With on-demand access, you can instantly rent additional
storage from a cloud provider and start using it right away. This saves time and effort,
allowing you to focus on your project instead of worrying about storage.
Difference with Elasticity:
· On-Demand Access: Focuses on the ability to obtain and use resources instantly
whenever needed.
· Elasticity: Focuses on the automatic adjustment of resources based on real-time
demand to maintain performance and efficiency.
6.2.2 Types of Cloud Services
There are different types of cloud services that cater to various needs. Cloud services are
typically categorized into three main types: Infrastructure as a Service (laaS), Platform as
a Service (PaaS), and Software as a Service (SaaS). Each type offers different levels of
153
control, flexibility, and management, catering to various needs and use cases.
6.2.2.1 Infrastructure as a Service (laaS)
laaS offers basic computing infrastructure such as servers, storage, and networking on a
pay-as- you-go basis. Users have control over the operating systems, applications, and
storage, but not the underlying physical infrastructure.
Example: Amazon Web Services (AWS) allows users to rent virtual servers to run their
applications. Microsoft Azure and Google Compute Engine are other popular laaS
providers.
6.2.2.2 Platform as a Service (PaaS)
PaaS offers a complete development and deployment environment in the cloud. It
includes infrastructure (servers, storage, and networking), middleware, development
tools, and management services. Developers can focus on coding and deploying
applications without managing the hardware and software layers.
Example: Google App Engine allows developers to build and deploy applications using
a variety of programming languages. Other examples include Microsoft Azure App
Services and Heroku.
6.2.2.3 Software as a Service (SaaS)
SaaS provides access to software applications that are hosted and managed by the
service provider. Users simply subscribe to the service and use it over the internet. This
model is convenient for end-users as it requires no hardware management or software
updates. Example: Google Workspace (formerly G Suite) includes applications like
Gmail, Google Docs, and Google Drive. Other examples are
Microsoft Office 365 and Salesforce.
Class Activity
Research and identify a cloud service provider (e.g„ AWS, Azure, Google Cloud)
and describe how its services are used in a real-world scenario. Present your
ndings to the class.
155
applications to the public cloud to handle increased load, while keeping critical data
secure in the private cloud.
6.2.3.4 Multi-Cloud
A multi-cloud approach uses multiple cloud services from different providers. This
model helps avoid dependency on a single provider and can enhance reliability and
performance.
Example: A company might use Google Cloud Platform for its data analytics, Microsoft
Azure for its enterprise applications, and Amazon Web Services for its backup and
disaster recovery. This ensures that if one provider experiences issues, the company can
still rely on other services.
6.2.4 Comparing Deployment Models
Each cloud deployment model has its own advantages and disadvantages, depending
on the specific needs and goals of the organization.
· Comparison: Public clouds are cost-effective but less secure. Private clouds are
more secure but expensive. Hybrid clouds offer flexibility, while multi-clouds provide
resilience.
6.3 Applications and Implications of Cloud Computing
This section explores key applications of cloud computing and discusses its implications.
6.3.1 Applications of Cloud Computing
Cloud computing has revolutionized the way businesses and individuals manage,
process, and store data. Its diverse applications span various sectors, offering scalable
and cost-effective solutions that enhance efficiency and innovation.
From hosting websites and running applications to providing data storage and
facilitating collaboration, cloud computing supports a wide array of functions that are
essential in today's digital age. By leveraging the power of the cloud, organizations can
streamline operations, reduce IT costs, and rapidly respond to changing demands. This
subsection explores the multifaceted applications of cloud computing and how they are
transforming industries and everyday life.
6.3.1.1 Data Storage
Cloud storage allows users to save data on remote servers rather than on local devices.
This makes it easier to access data from anywhere and share it with others.
Example: Services like Google Drive and Dropbox provide cloud storage solutions that
let users store and share files online. Businesses can use cloud storage to keep backups
of their data, ensuring it is safe from local hardware failures or other issues.
6.3.1.2 Web Hosting and Content Delivery
Cloud computing provides the infrastructure needed to host websites and deliver
content efficiently to users around the world.
Example: Platforms like Amazon Web Services (AWS) and Microsoft Azure offer web
156
hosting services that allow businesses to run their websites on cloud servers. Content
delivery networks (CDNs) such as Cloudflare help deliver website content quickly by
caching it on servers close to the end-users.
6.3.1.3 Machine Learning and Al in the Cloud
Cloud computing offers powerful tools for developing and running machine learning
models and artificial intelligence applications.
Example: Google Cloud AI and AWS SageMaker provide cloud-based platforms for
building, training, and deploying machine learning models. These services make it easier
for data scientists and developers to create AI solutions without needing extensive local
computing resources.
6.3.2 Implications of Cloud Computing
While cloud computing offers numerous benefits, it also brings various implications that
need to be considered.
6.3.2.1 Data Security
Security is a significant concern in cloud computing. Storing sensitive data on remote
servers introduces risks such as data breaches and loss.
· Security Challenges: Cloud providers implement robust security measures, but
users must also take steps to protect their data. Issues such as data breaches,
unauthorized access, and loss of data can occur.
· Security Measures: To mitigate risks, users should use encryption, strong
authentication methods, and regularly review their security policies. Providers often
offer tools to help manage and secure data.
6.3.2.2 Scalability and Resource Management
Cloud computing allows for scalability, meaning resources can be adjusted according to
demand. However, effective resource management is essential to avoid unnecessary
costs and ensure optimal performance.
· Scalability: Cloud services can automatically scale resources up or down based on
demand, such as adding more servers during peak times and reducing them when
demand decreases.
· Resource Management: Proper management practices, such as monitoring
resource usage and optimizing performance, help control costs and ensure efficient
use of cloud resources.
6.3.2.3 Cost Considerations
While cloud computing can be cost-effective, it requires careful financial management.
Users pay for what they use, and costs can quickly add up if not monitored.
· Cost Management: To manage costs, users should regularly review their cloud
usage and spending, optimize resource allocation, and take advantage of pricing
plans that fit their needs.
157
6.3.2.4 Compliance and Regulatory Issues
Organizations must ensure that their use of cloud services complies with legal and
regulatory requirements, which can vary by region and industry.
· Compliance: Organizations need to adhere to regulations related to data privacy,
security, and industry-specific standards. Cloud providers often offer tools and
features to help meet these requirements.
Class Activity
Create a list of cloud-based services you use or are familiar with. For each
service, describe how it benets you or your organization and any security
measures you use to protect your data.
159
6.4.1.2 Blockchain Components
Several key components make up a blockchain system:
· Node: A node is a computer that participates in the blockchain network. Each node
maintains a copy of the blockchain and helps validate transactions and blocks.
· Ledger: The ledger is a digital record of all transactions that have occurred on the
blockchain. It is distributed across all nodes, ensuring that everyone in the network
has access to the same information.
· Block: A block is a collection of transactions that are bundled together. Each block
contains a unique identifier (hash), a reference to the previous block (parent hash),
and a list of transactions.
· Transaction: A transaction is an individual entry in the blockchain. It represents the
transfer of assets or information between participants in the network.
· Blockchain Protocol: The blockchain protocol defines the rules and procedures for
how transactions are validated, how blocks are added to the chain, and how
consensus is achieved. It ensures the integrity and security of the blockchain
network.
6.4.1.3 Peer-to-Peer Network and Its Usage in Blockchain
A peer-to-peer (P2P) network is a system where computers, called nodes, communicate
and share resources directly with each other without relying on a central server. Each
node in the network can act as both a client and a server, making the network more
robust and decentralized.
For example, in a file-sharing network, users can download files directly from each
other's computers rather than from a single central server. This makes the process faster
and more efficient, as multiple users can share parts of the file simultaneously.
6.4.2 Use Cases of Blockchain Technology
Blockchain technology has a wide range of applications beyond cryptocurrency. Some
notable use cases include:
· Cryptocurrencies: Blockchain is the underlying technology for cryptocurrencies like
Bitcoin and Ethereum. It enables secure, decentralised digital transactions without
the need for intermediaries.
· Supply Chain Management: Blockchain can be used to track and verify the
movement of goods through the supply chain. This transparency helps prevent
fraud, reduce errors, and ensure the authenticity of products.
· Healthcare: In healthcare, blockchain can securely store patient records, manage
medical data, and ensure that only authorised individuals have access to sensitive
information.
· Voting Systems: Blockchain can be used to create secure and transparent voting
160
systems, ensuring that votes are accurately recorded and counted, and reducing the
risk of election fraud.
In Figure 6.3, the connections between different entities in a supply chain are illustrated.
The blockchain records interactions between suppliers, manufacturers, fabricators,
intermediaries, retailers, and customers. Each transaction is securely logged on the
blockchain, making it possible to track the journey of a product from its origin to the end
consumer. For instance, when a supplier delivers raw materials to a manufacturer, a
record is created and added to the blockchain. This process continues at each stage, with
the fabricator, intermediary, and retailer all contributing to a transparent and verifiable
history of the product. Ultimately, the customer can access this data to confirm the
product's origin and ensure it meets the expected standards.
162
Some artists use blockchain to sell digital art. Each piece of art has a
unique digital signature that proves it's the original.
163
6.5.3 Data Security in Blockchain
Data security in blockchain ensures that information stored in a blockchain is protected
from unauthorized access, tampering, or loss. To explain this in simple terms, let's use an
example that relates to something we encounter daily: sending a letter through the mail.
Example: Sending a Secure Letter
Imagine you want to send a letter containing important information to a friend. You
want to make sure that no one else can read or change the letter while it's being
delivered.
· Sealing the Letter (Encryption): Before sending the letter, you place it in a special
envelope that can only be opened by your friend. This is like encryption in
blockchain, where the data is turned into a code that only the intended recipient (or
those with the right key) can understand as shown in Figure 6.5.
· Signing the Letter (Digital Signature): You then sign the envelope with your
unique signature. This signature is known to your friend, so they can be sure the
letter came from you and hasn't been altered. In blockchain, this is called a digital
signature, which ensures that the data comes from a legitimate source and hasn't
been tampered with.
Do you know? Big companies like Amazon and Microsoft use their
powerful computers to help run blockchain networks.
Amazing Fact: With serverless architectures, you can scale your application automatically
in response to demand, ensuring that you only use and pay for the resources you need!
Class Activity
Think about how integrating blockchain with AI or loT could benefit your
community. Discuss with your classmates and propose a project that
leverages these technologies to solve a local problem.
In conclusion, the future trends and innovations in cloud computing and
blockchain are driving significant advancements in technology. Edge
computing and serverless architectures are enhancing the efficiency and
scalability of cloud computing, while Blockchain 2.0 and the integration of
blockchain with other technologies are expanding its applications and
capabilities. These emerging trends are set to revolutionize various industries,
offering new opportunities for innovation and growth.
Summary
· Emerging technologies are new tools, systems, and methods that are currently
being developed or have just started to be used.
· AI refers to machines and software that can think and learn like humans.
· Cloud computing allows people to store and access data and applications over
the internet instead of on a local computer or server.
· Blockchain is a secure way to record and share information across many
computers, making it almost impossible to change or hack.
· loT connects everyday objects, like refrigerators, cars, and even clothes, to the
internet. This allows them to send and receive data, making our lives more
convenient.
167
· AR adds digital elements to the real world using devices like smartphones or
glasses.
· VR creates a completely virtual environment that you can interact with using
special equipment.
· Quantum computers use the principles of quantum physics to process
information much faster than traditional computers.
· Biotechnology involves using living organisms, like bacteria and plants, to
create new products or solve problems.
· Virtualization is a technology that allows a single physical machine to run
multiple virtual machines.
· Scalability means you can add more resources when you need them.
· On-demand access means that you can use computing resources whenever you
need them, without waiting for a long setup process.
· laaS offers basic computing infrastructure such as servers, storage, and
networking on a pay-as- you-go basis.
· PaaS offers a complete development and deployment environment in the
cloud. It includes infrastructure (servers, storage, and networking), middleware,
development tools, and management services.
· A peer-to-peer (P2P) network is a system where computers, called nodes,
communicate and share resources directly with each other without relying on a
central server.
171
UNIT Legal and Ethical Aspects
7 of Computing System
Student Learning Outcomes
172
Introduction
In today's digital world, computing systems play a crucial role in every aspect of our lives,
from personal devices to complex networks. As these systems become more integrated
into our daily routines, understanding the legal and ethical considerations associated
with their use is essential. This chapter delves into various aspects of digital technology,
including terms of use, privacy and security threats, and the digital divide. The legal and
ethical challenges in computing cover a range of issues such as data protection,
intellectual property rights, and compliance with relevant laws. Ethical considerations
address privacy, fairness, and the broader societal impacts of technology.
7.1 Understanding Terms of Use
“Terms of Use”, also called Terms and Conditions or Terms of Service, are legal
agreements that outline how a service or product can be used. These terms are set by the
provider (like a website, app, or software company) and must be agreed upon by the
user. The main purpose is to establish a fair and transparent relationship between the
provider and the user, ensuring that both parties understand their rights and
obligations.
Examples: When you sign up for an email service like Gmail, you are required to agree to
Google's Terms of Use. These terms explain how you can use your email account, the
types of content you are prohibited from sharing, and how Google handles your
personal data. Similarly, when we use a Pakistani online shopping platform like Daraz,
the Terms of Use may include clauses about payment methods, return policies, and
delivery procedures, ensuring that customers are aware of what to expect and what is
expected from them.
7.1.1 Importance
Understanding Terms of Use is important for several reasons:
1. Protection of Rights: Terms of Use protect users by defining their rights, such as
the right to privacy, the right to receive certain levels of service, and the right to
seek redress if things go wrong.
Example: When we use a food delivery service in Pakistan like Foodpanda, the
Terms of Use will specify what happens if your order is incorrect or if the delivery
is delayed.
2. Clarity and Transparency: These terms provide clarity and transparency about
what users can expect from a service. They explain what the service provider will
deliver, under what conditions, and what actions are not permitted. This prevents
misunderstandings and helps users make informed decisions.
Example: If we use a mobile phone for sending or receiving payments, the Terms
of Use will outline transaction limits, fees, and the process for reporting
173
unauthorized transactions.
3. Legal Safeguards: For businesses, Terms of Use act as a safeguard against
misuse of their services. They set boundaries to protect the company from
potential legal issues caused by users not adhering to the rules.
Example: A Pakistani online education platform may include terms that prohibit
the sharing of course content without permission, protecting their intellectual
property.
7.1.2 Common Clauses and Conditions
Terms of Use usually contain several common clauses, which are designed to protect
both the provider and the user. These clauses include:
1. User Obligations: These clauses outline what is expected from the user.
Example: In Pakistan, popular ride-sharing apps such as Careem include terms
that require users to provide a valid phone number and prohibit the misuse of
the service for non-transportation purposes.
2. Limitations of Liability: These clauses limit the service provider's liability if
things go wrong.
Example: In Pakistan, if you use an online banking service and the app is
temporarily down, the bank's Terms of Use will typically limit their liability for
such disruptions.
3. Privacy and Data Use: Privacy clauses explain how a company will collect, use,
and protect user data. This is particularly important given the increasing
concerns around data privacy.
Example: If you use a messaging app like WhatsApp, the Terms of Use will
outline how your messages are stored and protected.
4. Intellectual Property Rights: These clauses protect the content owned by the
service provider, such as logos, software, and other proprietary materials.
Example: Pakistani news website may include terms that prohibit users from
copying and distributing their articles without permission, ensuring that their
content is not misused or misrepresented.
5. Termination of Service: This clause explains the conditions under which the
provider can terminate a user's access to the service.
Example: Social media platforms like Facebook have terms stating that they can
suspend or terminate accounts that violate community standards, such as
accounts that spread hate speech or misinformation.
7.1.3 Legal Ramifications
Violating the Terms of Use can lead to serious legal consequences. Users can be fined,
sued, or banned from using the service.
Examples: Using software without a proper license may result in legal action for
174
software piracy. Companies that uses unlicensed software face legal risks and
cybersecurity threats. Another example is violating the Terms of Use of a digital payment
service like PayPak. Engaging in fraudulent activities or unauthorized transactions may
result in legal penalties, including fines or criminal charges.
7.1.4 Ethical Considerations
Ethical considerations in Terms of Use encompass fairness, transparency, and respect for
user rights. It is essential for companies to ensure that their terms are clear,
straightforward, and not overly complex or deceptive. Providers are ethically obligated
to ensure that users fully understand the terms to which they are agreeing, rather than
obscuring critical information in lengthy or confusing documents.
Example: In Pakistan, when users sign up for an online course, the terms should clearly
specify whether a certificate will be awarded, how personal data will be handled, and
whether there are any additional fees. It is ethically imperative that educational
platforms avoid misleading users into believing a course is free if there are, in fact,
hidden costs involved.
7.1.5 Personal Rights
Personal rights within Terms of Use encompass the right to privacy, the right to be
informed, and the right to withdraw consent. It is essential for users to be aware of their
rights and understand how to exercise them.
Example: Under Pakistan's Personal Data Protection Bill, users have the right to access
their data and request corrections or deletions. When engaging with services like local e-
commerce websites, users have the right to know how their personal information, such
as addresses and phone numbers, will be utilized. If a user decides to discontinue using
the platform, they have the right to delete their account and data, ensuring that their
personal information is no longer retained or used.
Class Activity
Divide students into groups and assign each group a different Terms of Use
document. Each group should highlight key clauses such as User Obligations,
Privacy and Data Use, Limitations of Liability, and Termination of Service.
Afterward, distribute a worksheet with questions asking about the main
responsibilities of users, how user data is handled, specified limitations of
liability, and conditions for service termination. Finally, have students review
and summarize the key points and important clauses of the Terms of Use from
a frequently used website or app.
175
7.2 Privacy and Security Threats
In today's digital world, privacy and security threats are prevalent concerns that affect
individuals and organizations alike. These threats have the potential to compromise
personal information, financial data, and overall online security. A comprehensive
understanding of these threats is essential for safeguarding against potential risks and
ensuring the protection of sensitive information. There are some main types of privacy
and security threats.
7.2.1 Types of Security Threads
There are five primary categories of security threats of using online services.
7.2.1.1 Spam
Spam refers to unwanted messages that you receive on your email or phone.
Example: You may receive numerous text messages from unknown numbers offering
products or services that you did not ask for. In Pakistan, these messages may include
offers for fake prizes or low-cost loans. Such messages can be irritating and waste your
time. They can also attempt to trick you into providing personal information or money.
7.2.1.2 Spyware
Spyware is a type of harmful software that secretly watches what you do on your
computer or phone.
Example: If you download a free app from an unreliable source, it may install spyware on
your device. This spyware can secretly monitor your online activities, such as the
websites you visit or the information you enter, without your knowledge.
7.2.1.3 Cookies
Cookies are small files that websites place on your device when you visit them. They help
the website remember things like your login details and personal preferences.
Example: When you visit an online shopping site in Pakistan, cookies save your login
information so you do not need to enter it each time you visit. However, cookies can also
track your online activities, such as the products you view, to show you advertisements
related to your interests. This tracking helps in providing personalized ads but also
means that your browsing activities are being observed.
7.2.1.4 Phishing
Phishing is a type of scam where someone pretends to be a trustworthy organization to
trick you into giving away your personal information.
176
Example: You may receive an email that looks like it comes from your bank, asking you
to click a link and enter your account details. If you follow these instructions, your money
could be at risk because the email is a fake.
Pharming
Pharming is a sophisticated technique where users are redirected to a fake website
without their knowledge.
Example: Imagine you want to access your online banking account, but due to a
pharming attack, you are sent to a counterfeit site that looks just like your bank's real
site. If you enter your login information on this fake site, the scammer collects your
details. In Pakistan, this can occur if a hacker changes the web address you type into your
browser, leading you to a fraudulent site that closely resembles the legitimate one.
7.2.2 Characteristics of Security Threats
Security threats have different features and ways of causing harm.
Spam, is often easy to recognize because it comes in large amounts and includes
unwanted advertisements. Spyware, in contrast, operates quietly in the background
and is not easily noticeable. Spam emails may have odd offers or suspicious links that
make them stand out, while spyware works silently to monitor your activities without
obvious signs.
Each type of security threat has a unique method and purpose. Spam aims to promote
products or trick you into buying something. Spyware is designed to secretly gather
your personal information. Cookies collect data on your browsing habits. Phishing
attempts to deceive you into revealing your personal details. Pharming redirects you to
fake websites to steal your information. Understanding these differences is important
for protecting yourself from each type of threat.
7.2.3 Consequences and Severity
Security threats can have serious effects. Spam is often just a nuisance, but spyware can
lead to significant privacy issues by stealing your personal data. Cookies may invade
your privacy by tracking your online activities. Phishing and pharming can cause
financial losses and give unauthorized access to your accounts. The impact of these
threats varies, but all can affect your safety and privacy. It is important to be aware of
these threats to prevent problems and keep your personal information secure.
177
Over 90% of phishing attacks are carried out through email. These
scams often look like legitimate communications from trusted
organizations, making it crucial to verify the source before clicking on
any links or providing personal information.
178
7.2.4.5 Guarding Against Pharming
Pharming is when attackers redirect you from a legitimate website to a fake one to steal
your information.
Example:
If you type in the URL for your bank's website, pharming can send you to a fake website
that looks just like your bank's site. To guard against pharming, always check that the
website's address is correct and secure (look for “https://" and a padlock symbol in the
address bar).
Effective online security involves using multiple strategies like spam filters, antivirus soft-
ware, and careful cookie management to cover various threat types. Combining different
security techniques provides better protection against online threats.
179
3. Educational Barriers: Lack of digital literacy is another significant factor contributing
to the digital divide. Even when the technology is available, individuals may not
know how to use it effectively due to a lack of proper education and training.
4. Social Barriers: Age, gender, and disability can also affect access to technology. For
example, older adults may be less inclined or able to use new technologies, and
women in some regions may face cultural barriers that limit their access to ICT.
7.3.2 Impacts of the Digital Divide
The digital divide has far-reaching impacts on individuals and society as a whole. These
impacts can exacerbate existing inequalities and create new ones.
7.3.2.1 Educational Inequality
Access to the internet and digital tools is increasingly essential for education. Students
who lack access to these resources are at a significant disadvantage.
Example: During the COVID-19 pandemic, when schools in Pakistan and around the
world shifted to online learning, students from low-income families or rural areas
struggled to keep up with their studies due to a lack of internet access or devices. This
has led to a widening of the educational gap between different socio-economic groups.
7.3.2.2 Economic Disparities
The digital divide also has significant economic implications. In today's economy, many
jobs require at least basic digital skills. Those without access to technology or the
internet may find it challenging to secure employment, leading to higher
unemployment rates in already disadvantaged communities.
Example: In Pakistan, access to online job portals and digital banking services is often
limited to those in urban areas, further widening the economic gap between urban and
rural populations.
7.1.2.3 Social and Civic Participation
The digital divide can also affect social and civic participation. Access to social media,
online news, and digital government services allows individuals to stay informed and
engaged in civic activities. However, those without access are often excluded from these
opportunities, leading to a lack of representation and participation in democratic
processes.
Example: In Pakistan, access to e-government services is more readily available in cities,
leaving rural populations with limited means to participate in governmental processes
or access social services.
180
7.2.2.4 Health Disparities
The digital divide can lead to unequal access to health information and services. Digital
platforms provide valuable resources for health education, telemedicine, and
appointment scheduling. Without access to these resources, individuals may experience
poorer health outcomes due to a lack of timely information and medical care.
Example: In Pakistan, rural communities with limited internet access may struggle to
find reliable health information online or participate in telemedicine consultations. This
can result in delays in diagnosing and treating health conditions compared to those who
have better access to digital health services.
7.2.2.5 Digital Literacy Gap
A significant digital divide also creates a gap in digital literacy. Individuals who do not
have access to technology may not develop essential digital skills, further reinforcing the
divide between those who are tech-savvy and those who are not. This gap can affect
their ability to navigate digital environments effectively and make use of online
resources.
Example: In Pakistan, people who lack access to computers and the internet may miss
out on opportunities to learn and practice digital skills. This can hinder their ability to use
online tools for everyday tasks, such as applying for jobs or accessing government
services, compared to those with regular access to digital technologies.
7.3.3 Bridging the Digital Divide
Bridging the digital divide means making sure everyone has equal access to technology
and the internet. This is important for giving everyone the same chances to learn and
grow. Here are some ways to do it:
1. Government Initiatives: The government can help by building the
infrastructure needed for internet access in areas where it's not available.
Example: In Pakistan, the Universal Service Fund (USF) works to bring internet
services to villages and remote areas where people might not have had access
before.
2. Educational Programs: Schools and community centers can teach people
how to use technology.
Example: Digital literacy programs can help students and adults learn how to
use computers and the internet for education and daily tasks.
3. Public-Private Partnerships: When the government teams up with
businesses and nonprofits, they can make technology more affordable.
181
The Government of Pakistan has launched several initiatives to
increase internet access in rural areas, including the introduction of
mobile broadband services in remote regions. Despite these efforts,
many areas still lack reliable connectivity, highlighting the ongoing
challenge of bridging the digital divide.
Class Activity
Think about your own community. Are there people who may not have access
to the internet or digital devices? What can be done to help them? Write a
short paragraph on how your school or community can help bridge the digital
divide.
182
Example: A research paper written by scientists who conducted the study is a primary
source. In contrast, a summary of the research written by someone else would be a
secondary source.
7.4.1.5 Critical Thinking Skills
Critical thinking skills are necessary for analyzing and evaluating information. This
means questioning the information, considering different perspectives, and making
informed decisions.
Example: If you read about a new technology, using critical thinking means looking at
various sources and viewpoints before forming an opinion.
7.4.1.6 Red Flags
Red flags are signs that indicate a source might be unreliable. These include lack of
author information, sensational headlines, or sources that do not cite their references.
Example: A website with no clear author or contact information might be unreliable.
7.4.1.7 Understanding Bias
Understanding bias involves recognizing that every source may have a certain viewpoint
or agenda. Example: A news website that only reports on one side of an issue might be
biased. It is important to consider multiple viewpoints and check if the information is
presented fairly.
185
7.6.3 Cybersecurity Awareness
Cybersecurity awareness involves understanding and implementing practices to protect
oneself from online threats.
A Cyber Crime can be reported at NR3C-FIA available at
https://www.nr3c.gov.pk
Class Activity
Try to learn how a student can become a Cyber Scout at NR3C-FIA by visiting
https://www.nr3c.gov.pk
188
3. Which of the following is a harmful software that secretly monitors your computer or
phone activities?
(a) Spam
(b) Cookies
(c) Spyware
(d) Pharming
4. Which of the following threats involves redirecting users to fake websites without
their knowledge?
(a) Phishing
(b) Spam
(c) Spyware
(d) Pharming
5. How does the digital divide affect education?
(a) It improves learning for all students
(b) It has no impact on education
(c) It creates inequality in access to digital learning resources
(d) It makes traditional teaching methods obsolete
6. What does data provenance refer to?
(a) The cost of accessing the information.
(b) The history and origins of the data.
(c) The popularity of the information source.
(d) The translation of information into multiple languages.
7. Why is understanding bias important when evaluating information?
(a) To ignore opposing viewpoints.
(b) To recognize and account for a source's viewpoint or agenda.
(c) To validate all sources as equally reliable.
(d) To avoid evaluating the information altogether.
8. Which of the following is a positive impact of computing systems on society?
(a) Increased spread of misinformation
(b) Improved accessibility to information
(c) Privacy concerns
(d) Unequal access to technology
9. What does ethical use of information involve?
(a) Copying content without permission.
(b) Respecting copyright and avoiding plagiarism.
(c) Ignoring data sources when sharing information.
(d) Using unverified information for reports.
189
10. Which of the following is NOT a sign of responsible digital behavior?
(a) Using secure websites for personal data sharing.
(b) Spreading false information on social media.
(c) Respecting others' privacy online.
(d) Reporting suspicious online activities.
Short Questions
1. Why is it important for users to understand Terms of Use?
2. Differentiate between phishing and pharming.
3. Describe how cookies can be both beneficial and invasive to privacy. Give an
example of each scenario.
4. Identify two impacts of the digital divide on social and civic participation.
5. What are the key steps involved in evaluating information sources?
6. Explain how computing systems have impacted communication in society.
7. How does responsible data sharing contribute to ethical use of information?
8. Describe two ways to recognize online threats and prevent cybersecurity risks.
Long Questions
1. Explain the common clauses found in Terms of Use and describe how they protect
both the service provider and the user.
2. Explain the concept of bridging the digital divide and discuss the roles of
government initiatives in addressing this issue. Provide relevant examples from
Pakistan.
3. Explain how critical thinking skills contribute to responsible information utilization.
Provide examples of how these skills can be applied in real-life scenarios.
4. Discuss the importance of collaborative problem solving in a digital environment
and provide examples of how human-machine collaboration can enhance this
process.
5. Explain the concept of creating accessible digital content and describe strategies to
ensure digital inclusivity for individuals with disabilities.
190
UNIT Online Research
8 and Digital Literacy
191
Introduction
This chapter illustrates the fundamental aspects of online research and digital literacy,
which are essential for effectively navigating and utilizing the vast array of information
available on the internet. It introduces key concepts related to conducting online
research, including advanced search techniques and effective management of digital
resources. Additionally, the chapter covers the importance of formulating clear research
inquiries, understanding research ethics, and recognizing intellectual property rights.
Mastering these skills will enable students and researchers to perform rigorous and
ethical research while ensuring proper use and protection of digital content.
8.1 Introduction to Online Research and Digital Literacy
Online research is the activity of finding information on the internet about a particular
topic. It involves using various online sources, such as articles, reports, or videos, to
gather knowledge. The goal of online research is to collect correct, trustworthy, and
current information that helps in understanding a topic or solving a problem. When
conducting online research, it is essential to check if the information comes from a
reliable source. This can include official government websites, educational institutions,
or well-known newspapers. By comparing information from multiple sources, one can
ensure the accuracy of the findings.
8.1.1 Importance of Online Research
Online research is important because it allows people to access a wide range of
information quickly and easily. In today's world, where almost everything is connected
to the internet, knowing how to search for and use online information is a valuable skill.
It helps students to complete their homework, allows professionals to stay updated in
their fields, and assists everyone in making informed decisions. However, not all
information on the internet is correct. Some websites may provide false or misleading
details. It is necessary to know how to find information from reliable sources to ensure
that the facts you gather are accurate and useful.
8.1.2 Types of Online Research
Online research can be categorized into different types based on the purpose and the
kind of information needed. The most common types of online research are:
1. General Information Research: It involves finding basic information on a topic. It
is useful for gaining an overview or understanding the main points. One can use
search engines like Google to find articles, blog posts, or videos that provide
general knowledge.
2. Academic Research: This type of research focuses on finding scholarly
information for educational purposes. It involves searching for books, research
192
papers, or articles from educational websites, libraries, or databases. Academic
research provides detailed and reliable information that is often written by
experts.
3. Market Research: This type is used by businesses and entrepreneurs to
understand market trends, customer behavior, and competition. Market
research helps businesses make informed decisions about launching new
products or services.
4. Fact-Checking Research: This type is used to verify if the information is accurate.
It involves checking multiple reliable sources to confirm the correctness of facts.
5. Health Research: This type involves finding information related to health issues,
medical treatments, or healthcare services. It helps people learn about
symptoms, treatments, and ways to stay healthy by using reliable health
websites and medical journals.
8.1.3 Digital Literacy
Digital literacy is the ability to use digital tools, such as computers, smartphones, and the
internet, to find, understand, create, and share information. It involves several skills,
including using search engines to look up information, assessing whether online
sources are reliable or not, and protecting personal information while using digital
platforms.
Example: If a student needs to gather information for a science project. The student uses
a search engine to find articles and videos related to the topic. Digital literacy helps the
student decide whether the sources found are trustworthy, such as checking if an article
is from a reputable source like a university or a well-known organization.
8.1.4 Key Components of Digital Literacy
Digital literacy includes several important skills that help people use technology
effectively. The key components of digital literacy are explained below.
Using Technology
Using technology involves operating devices like computers, tablets, and smartphones.
It includes knowing how to open programs, use applications, and navigate websites.
Example: If a student uses a computer to write a report for school. They need to know
how to use word processing software to type and format their report.
Searching for Information
Searching for information means using search engines to find data on the internet. This
skill includes entering relevant keywords and refining search results to locate useful
information.
Example: A farmer in Punjab wants to learn about new crop irrigation methods. They
use Google to search for terms like “modern irrigation techniques for wheat”.
193
Evaluating Sources
Evaluating sources involves checking if the information you find online is reliable. This
includes looking at who created the content and whether it comes from a trustworthy
source.
Example: A teacher in Lahore finds a website claiming to have the latest educational
methods. They check if the website is run by an educational institution or a credible
organization before using its information.
Creating Digital Content
Creating digital content involves making your own materials, such as writing articles,
creating presentations, or editing photos. It requires knowledge of different software
and tools.
Example: A student in Karachi creates a PowerPoint presentation for a class project.
They use presentation software to add slides, text, and images.
Online Safety and Privacy
Online safety and privacy involve protecting personal information and staying safe on
the internet. This includes using strong passwords and recognizing potential online
threats.
Example: A person in Islamabad uses social media and sets their privacy settings to
control who can see their personal information. They also avoid clicking on suspicious
links to protect their online security.
8.1.5 Advanced Information Retrieval Techniques
Finding information online can be more effective if you use advanced techniques. These
techniques help you get better results from search engines and find exactly what you
need.
Effective Use of Search Engines
Search engines like Google are powerful tools for finding information. To use them
effectively, you need to know how to enter your search queries in a way that gives you
the best results.
Example: If a female needs information on traditional pakistani recipes. Instead of just
typing “recipes”, the student can type “traditional pakistani recipes” to get more specific
results.
Choosing Effective Keywords
Keywords are the words you type into a search engine. Choosing the right keywords
helps you find relevant information quickly. Think about the most important words
related to your topic and use them in your search.
Example: A farmer in Punjab wants to learn about “organic farming techniques”. By
194
using the keywords “organic farming” instead of just “farming”, the farmer will find more
relevant information.
Using Boolean Operators ("AND", "OR", "NOT")
Boolean operators are special words that help you refine your search. They are “AND”,
“OR”, and “NOT”.
• AND is used to include multiple terms in your search.
Example: If you search for “agriculture AND irrigation”, you will get results that
include both terms.
• OR is used to find results that include either of the terms.
Example: “Crops OR vegetables”, will show results that include either word.
• NOT is used to exclude certain terms from your search.
Example: “Farming NOT pesticides” will show results about farming that do not
mention pesticides.
Advanced Search Features
Many search engines offer advanced search features that allow you to filter results by
date, location, and more. These features help you find the most relevant and recent
information.
Example: If a student in wants to find the latest news on “Pakistan's education policy”,
They can use the advanced search feature to filter results by the past year to find the
most recent articles.
Class Activity
1. Choose a topic that interests you (e.g., renewable energy, artificial
intelligence, or a historical event).
2. Use specific keywords to search for information online.
3. Find at least three sources of information and evaluate their reliability.
4. Write a short summary of what you found and include the links to your
sources.
Did you know that more than half of the world’s population uses the
internet? With so much information available, learning how to
research effectively online is a powerful tool for your education and
beyond.
Did you know that formulating good research questions is the first
step to a successful research project? A well-thought-out question
sets the direction for your entire study and helps you focus on finding
the right answers.
Note that by learning how to ask the right questions and making
informed guesses, you can design meaningful research projects that
contribute to our understanding of the world!
196
8.3.2 Effective Navigation and Managing Digital Information
When looking for information online, knowing how to search effectively is important. Start by
using specific keywords related to your topic. You can also use advanced search options to
narrow your results. Many online libraries and databases offer filters to help you search by date,
author, or subject. Once you have found useful resources, managing the information is crucial.
Save and organize digital copies of articles, take notes on key points, and keep track of your
sources for future reference. Using digital folders, note-taking apps, or reference managers helps
you stay organized and makes the research process smoother.
Example: Create a folder on your computer. Inside the folder, save PDFs of articles you find and
keep a document with important quotes or ideas.
Class Activity
1. Choose a topic for research and use an online library or open-access
repository to find at least three academic articles related to your topic.
2. Download the articles and save them in a designated folder.
3. Write a summary of each article, noting down key points and any useful
quotes.
4. Share your findings with the class, explaining how you found the articles
and how you organized your research.
Did you know that many universities around the world, including in
Pakistan, provide free access to thousands of academic journals and
research papers online? By learning how to navigate these digital
resources, you can find high-quality information for your studies
without leaving home!
Note that by effectively using digital resources and managing your
information, you can make your research process more efficient and
organized, leading to better results in your assignments and projects.
Did you know that ethical guidelines in research have been developed
over many years to protect participants and ensure that research
contributes positively to society? By following these guidelines, you
can help build trust in your work and contribute to the greater good.
Remember, being an ethical researcher means more than just
following rules—it’s about being honest, fair, and respectful in all your
research activities.
Class Activity
Objective: Help students identify different types of intellectual property in
their daily lives.
1. Ask students to bring to class a product they use regularly, such as a
mobile phone, a book, or a piece of clothing.
2. Have each student identify at least one type of intellectual property
associated with their product (e.g., the brand name, the design, or the
content).
3. Discuss how intellectual property rights protect these elements and why it
is important for the creators or companies.
Did you know that Pakistan has its own Intellectual Property
Organization (IPO)? This organization is responsible for registering
and protecting intellectual property rights in the country, helping to
ensure that creators and businesses are rewarded for their innovation.
200
Summary
This chapter provides a comprehensive overview of online research, digital literacy,
and intellectual property, focusing on essential skills and concepts in these areas. It
begins by highlighting the significance of online research and the various research
methods available. It then addresses digital literacy, covering key aspects such as
technology use, information retrieval, source evaluation, digital content creation, and
maintaining online safety and privacy. The chapter also explores advanced
information retrieval techniques and the formulation of research inquiries, including
research questions and hypotheses. Furthermore, it examines the use of digital
resources, research ethics, and the different types of intellectual property: patents,
trademarks, copyrights, industrial designs, and trade secrets emphasizing their
importance in protecting creative and innovative works.
201
(a) It is edited by a single expert
(b) It is published in a magazine
(c) It is reviewed by other experts in the field
(d) It is freely available online
6. Which of the following is a key purpose of online libraries?
(a) Providing access to entertainment
(b) Offering a variety of academic resources
(c) Promoting social media interaction
(d) Selling digital books and materials
7. Which of the following is an essential component of ethical research?
(a) Collecting as much data as possible regardless of participants' privacy
(b) Avoiding plagiarism and providing proper credit
(c) Publishing results only if they are positive
(d) Ignoring participant consent if the research is important
8. Which principle of research ethics focuses on being truthful and transparent in
reporting findings?
(a) Confidentiality (b) Integrity
(c) Informed Consent (d) Avoiding Bias
9. Which of the following is NOT a type of intellectual property?
(a) Patents (b) Trademarks
(c) Copyrights (d) Physical Properties
10. How can a company protect a trade secret?
(a) By registering it with the IPO
(b) By applying for a trademark
(c) By keeping the information confidential and using legal agreements
(d) By publishing it in a scientific journal
Short Questions
1. How can one ensure the reliability of information found through online
research?
2. Why is it important to evaluate the reliability of online sources?
3. Explain the difference between exploratory and explanatory research questions.
4. Explain the importance of hypothesis in research process.
5. Why is it important to use specific keywords when searching for information
online?
202
6. How can a researcher avoid bias in their study?
7. Describe the purpose of a trademark.
8. How does copyright differ from patent protection?
Long Questions
1. Discuss the different types of online research and their purposes, providing
examples for each type.
2. Explain the concept of digital literacy and its key components. How does it
contribute to effective use of digital tools and resources?
3. Explain the process of developing a clear and focused research question.
Illustrate your answer with examples of well-formulated and poorly-formulated
research questions.
4. Discuss the importance of research ethics in maintaining the credibility and
reliability of research findings. Explain how unethical practices could affect the
research community and society.
5. Discuss the various types of intellectual property and provide examples of each.
Explain how each type helps in protecting different kinds of creations and
innovations.
203
UNIT Entrepreneurship in
9 Digital Age
Student Learning Outcomes
204
Introduction
In this chapter we introduce the key aspects of entrepreneurship, focusing on the skills
and strategies necessary for business success. It covers the importance of innovation,
creativity, and problem-solving, emphasizing Design Thinking as a human-centered
approach to developing effective business solutions. The chapter guides readers
through creating a business plan, gathering market insights, and pitching ideas to
potential investors. It also touches on marketing and sales strategies, financial concepts,
and the significance of communication, collaboration, and iteration
in refining business ideas. Lastly, it highlights the role of innovation and creativity in
developing unique solutions and improving existing products and services.
9.1 Introduction to Design Thinking and Business Solutions
Let's explores how creative methods, like Design Thinking, help businesses tackle
challenges and better meet customer needs.
9.1.1 Design Thinking
Design Thinking is a method that helps us to look at problems from different angles.
Instead of just jumping to solutions, Design Thinking encourages us to first understand
the problem deeply. This method involves five key steps: Empathize, Define, Ideate,
Prototype, and Test.
· Empathize: This means putting yourself in someone else's shoes to understand
their feelings, needs, and challenges.
Example: If you are designing a new school bag, you would talk to students to
learn what they like and dislike about their current bags.
· Define: After gathering information, the next step is to clearly define the problem.
Using the school bag example, you might define the problem as: 'Students need
a lightweight, durable, and spacious bag that is comfortable to carry'.
· Ideate: Now it's time to brainstorm ideas. You can think of all possible solutions
without worrying if they are perfect. You might come up with ideas like a bag with
extra padding for comfort or one with compartments that make it easy to
organize books and supplies.
· Prototype: A prototype is a simple version of your idea that you can create
quickly. For the school bag, you might create a basic model using cardboard,
fabric, or even paper to show what it might look like.
· Test: Finally, you test your prototype to see if it works well. You could ask students
to try the bag and give feedback. Based on their comments, you can make
improvements until you have a final product that solves the problem.
9.1.2 Business Solutions
Business solutions are ways to help companies solve problems and work better.
205
Example: Imagine you run a small grocery store. If you notice that items are often out of
stock, a business solution could be to order more frequently or use software to track
inventory. These steps can help keep your shelves full and customers satisfied.
Business solutions are not just about fixing problems; they also help businesses grow
and improve. For instance, if more customers start shopping online, you might offer
home delivery services to meet their needs. This way, your business can keep up with
changes and continue to thrive.
9.1.3 How Does Design Thinking Apply to Business Solutions?
In the business world, Design Thinking helps companies create products and services
that people actually want and need. For example, a company might use Design Thinking
to develop a new app that makes it easier for people to order food online. By focusing on
the user's experience and testing different ideas, they can create a solution that is both
user-friendly and successful in the market.
Class Activity
Let's apply Design Thinking to a problem in your college. Imagine that
students are having trouble finding time to do homework because they have
too many after-school activities. How could you solve this problem?
1. Empathize: Talk to your classmates to understand how they feel about
the situation.
2. Define: Write down the main problem based on what you learned
from your classmates.
3. Ideate: In groups, brainstorm different ways to help students manage
their time better.
4. Prototype: Create a simple plan or schedule that could help students
balance their activities and homework.
5. Test: Share your plan with other students and see if they think it would
work. Make any changes needed.
This activity will help you practice Design Thinking and see how it can be
used to solve everyday problems.
208
Activity Instructions: Class Activity
1. Choose a business idea that interests you. It could be
something simple like a school bake sale or a new hobby club.
2. Write a business plan using the key parts we discussed:
· Executive Summary
· Business Description
· Market Analysis
· Organization and Management
· Products or Services
· Marketing and Sales Strategy
· Financial Plan
· Appendix (if needed)
3. Share your business plan with the class. Explain why you think your
business will be successful and how you plan to make it happen.
4. Discuss with your classmates about their plans and give constructive
feedback. This will help everyone improve their ideas and learn from
each other.
By following these steps, you'll have a solid foundation for starting your
own business and making your ideas come to life!
211
neighborhood. A business pitch would include:
• What the idea is: A juice shop that sells fresh, healthy, and affordable juices.
• Who the customers are: People in your neighborhood, especially those who
care about their health.
• Why it will work: There are no other juice shops nearby, and people are
becoming more health-conscious.
Some of the most famous companies in the world, like Apple and
Google, started with simple business pitches. The founders had to
explain their ideas clearly to get support and investment!
213
Class Activity
Imagine you are starting your own business selling a product of your
choice. Develop a marketing and sales strategy for your business. Consider
your target market, how you will reach them, and what sales tactics you will
use. Share your plan with the class.
In Pakistan, the e-commerce sector is rapidly growing, with more people shopping online
than ever before. Businesses that effectively market their products online can reach a
much wider audience.
214
the shop are Rs. 30,000, the profit would be:
Profit = Revenue — Costs = 50,000 — 30,000 = Rs. 20,000
Class Activity
Calculate the total amount to be repaid on a loan of Rs. 50,000 over one year at
an interest rate of 8%. Analyze how the interest rate impacts the total
repayment amount.
Think of this phase like designDid you know that one of the most powerful speeches in
history, the I Have a Dream speech by Martin Luther King Jr., is remembered not just for its
message but for the way it was delivered? The combination of storytelling, emotion, and
clear communication made it unforgettable.ing a new house. You need blueprints to show
where the rooms and furniture will go before you start building.
217
9.7 Collaboration and Iteration
9.7.1 Collaboration
Collaboration is when two or more people work together to achieve a common goal. It
involves sharing ideas, resources, and efforts to solve problems or create something
new. In Pakistan, collaboration can be seen in many areas, such as when students work
together on a group project, or when community members come together to organize
an event.
Class Activity
Imagine you and your classmates have been asked to create a science model
for an exhibition. Instead of each of you working separately, you decide to
collaborate. One student might be good at drawing diagrams, another at
building models, and someone else at explaining the project to others. By
collaborating, you combine your strengths and produce a better project than
any one of you could have done alone.
9.7.2 Iteration
Iteration means repeating a process with the aim of getting closer to a desired result. It
involves making changes and improvements based on feedback until the final outcome
is achieved. In everyday life, iteration can be seen in activities like cooking, where you
might adjust the ingredients and taste as you go until the dish is perfect.
Example: Suppose your class is designing a new logo for a school event. You begin with
an initial design and share it with your classmates for their opinions. Based on their
feedback, you revise the design, adjusting colors and shapes. You then seek more
feedback and make further changes. This cycle of designing, gathering feedback, and
refining continues until you have a final logo that everyone approves. This process
illustrates iteration.
Class Activity
Form groups of 4-5 students. Each group will create a simple poster on a topic
of your choice. After the first draft, exchange posters with another group for
feedback. Use their suggestions to improve your poster, then share the
updated version with the class.
Class Activity
Think of a problem in your college or community that needs a solution. In
groups, brainstorm creative ways to solve the problem. Present your ideas to
the class!
Summary
This chapter provides a comprehensive overview of essential entrepreneurship concepts
and skills. It begins by introducing entrepreneurship and the importance of innovation,
problem-solving, and value creation. The chapter explores Design Thinking, a method
for developing human centered solutions, and details how to create a business plan,
including market analysis and financial forecasting. It also covers gathering market
insights, pitching ideas, and implementing marketing and sales strategies. Financial
management, effective communication, and collaboration are discussed as key
components for business success. Finally, the chapter encourages innovation and
creativity, equipping students with the tools needed to start and sustain their own
ventures.
222
223