78% (18) 78% found this document useful (18 votes) 191K views 160 pages 11th Computer New Book 2025 Punjab Text Book Board
The document is a textbook on computer science, specifically focusing on software development, programming, algorithms, and emerging technologies, approved by the Punjab Curriculum and Textbook Board. It outlines key concepts such as the Software Development Life Cycle (SDLC), methodologies like Waterfall and Agile, and essential practices for project planning, quality assurance, and design. The content is structured to guide students through the fundamental aspects of software development, including practical applications and ethical considerations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save 11th Computer New Book 2025 Punjab Text Book Board For Later ple thd Slaps
(In the Name of Allah, the Most Compassionate, the Most Mercifull)
COMPUTER
SCIENCE
PUNJAB CURRICULUM AND
TEXTBOOK BOARD, LAHORE1 ort Single National Curriculus
¢™
pproved by the Board.
Al rights are reserved with the Punjab Curriculum and Textbook Board; Lahore:
No part of this textbook can be copied, translated, reproduced or used for preparation of
} test papers, guidebooks, keynotes and helping books
Contents
4 Introduction to Software Development 01
2 Pyttion Programming 30.
3 Algorithms and Problem Solving 65
4 Computational Structures 87
5 Data Analytics 123
6 Emerging Technologies | 150
7 Legal and Ethical Aspects of Computing System | 172
8 Online Research and Digital Literacy 191
9 Entrepreneurship in Digital Age 204
Answers 223,Authors
¢ Prof. Dr. Muhammad Atif
(PhO Computer Science)
Professor of Computer Stience, Lahore Garrison University
© Prof. Dr. Syed Wagar ul Qounain Jaffry
(PhD Computer Science) Chairman Dept. of IT,
University of The Punjab, Allama Iqbal Campus (Old Campus) Shahrah-e-Quaid-e-Azam, Lahore:
External Review Committee
© Dr. Arshad Ali © Dr. Mudasser Naseer
(PhD Computer Science and Telecommunication) (PhD Computer Science)
‘Associate Professor, Department Associate Professor(CS),
Head (Cyber Security), Department of CS & IT,
FAST Schoo! of Computing, National University University of Lahore Defense Road, Lahore
‘of Computer and Emerging Sciences, Lahore
Mrs. Tabinda Mugaddas ° Mr. Fahad Asif
Assistant Professor, Head of Department (CS), EST (CS),
Govt. Associate College for Women, Govt. Lab Higher Secondary School,
Gulshan Ravi, Lahore QAED Kasur.
Dir Curriculum and Compliance Dy, Direct (Graphics) Dy. Director (Science/Humanities)
Mr. Amir Riaz Ms. Aisha Sadiq Mr. Imtiaz Hussain
Supervision Design & Layout illustration
Mi. Jahanzaib Khan Mr Aleem UrRehman Mr, Ayat Ullah
5 Compute Sience)Introduction to
Software Development
Biro c ees
By the endof this chapter, students will be able to:
+ Define 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.
+ Planasoftware project by setting timelines, estimating costs, and managing risks.
* Recognize and apply quality assurance techniques to ensure software standards.
* Utilize Unified 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.Introduction
Software development is a systematic process that transforms user néeds into software
products: It involves a
Differentiating Functional and Non Functional Requirements:
Functional Requirements Non-Functional Requirements
‘Define specific behaviors or functions of Define the quality attributes and constraints,
the system —ofthesystem
‘What the system should do How the system should: perform
Example: User can borrow books Example: System should handle 1000
users simultaneously
rectly related to user interactions and —_ Related to. system performance, usability,
_system tasks reliability, etc.
Table 1.1; Comparison between Functional and Non-Functional Requirements,
1.1.4.4 Design
Inthe design phase, we plan out how the software will look and work. This is like drawing
a blueprint before building a house. During this phase, we:
* Create Diagrams: To show how different parts of the software will connect
and work together. For example, we draw a flowchart to map out the steps
the pragram will take to complete a task.
* Develop Models: To represent the software's structure, This could include
creating mockups of the user interface, showing what the program will look
like and how users will interact with it.
* Plan the Architecture: To decide the overall structure of the software,
including how different components will interact. This helps ensure that the
program is organized and functions smoothly.
* Specify Requirements: To define clearly what each part of the software
needs to do, ensuring that all features are planned out and nothing is
overlooked.
These steps help to ensure that the final software is well-organized, user-friendly, and
meets the needs of its users.
1.1.1.1 Development
In the development phase, the actual creation of the software begins. This is where
programmers weite 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
intoa pragramming language, sThink 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 {ree 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 softwares run under various conditions to see if it behaves correctly. This includes:
«Functionality Testing: Enstiring all features of the software work according
to the specifications.
*. Performance Testing: Checking if the software performs well under different
conditions; suchas 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'sneeds, 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 maves
to the deployment phase. Deployment is the process of making the software available
forusers to access and use. This often involves several steps:
* Installation: The software is installed on the user's systém of sérver. 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.
Deploying software is fike opening a new store? Once everythin:
set up, youwelcame customers (users) tostart using your product.1.4.4.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.
1.1 Software Development Methodologies
Software development methodologies are structured approaches: to software
development that guide the planning, creation, and management of software projects.
They help ensure that the development process is systematic, efficient, and produces
high-quality software.
1.1.1 Introduction te Software Process Models
Software process models are abstract representations of the processes involved in the
software development lifecycle. They provide a framework for planning, structuring, and
controlling the devélopment of software systems. The importance of software process
models liesintheirability to provide:
«Predictability: By following a defined process, teams can predict outcomes
and manage tisks more effectively.
* Efficiency: Structured methodologies streamline the development process,
reducing wasted effort.
* Quality: Adhering to a process mode) ensures that quality assurance
practices are integrated throughout the development lifecycle.
1.1.1.1 Waterfall Model
The Waterfall Model is a straightforward approach to software development where each
phase of the project must be completed before the next one begins, Think of it like a
waterfall flowing from one stage to the next. This model is linear and sequential,
meaning that you move through each phase in order, without going back to previous
phases once they are completed as hown in Figure 1.2. The main phases af the Waterfall
Model are:
* Requirements: Gather and document what the software needs to do.
Design: Plan how the software will be built and how it will look:
Implementation: Write the actual code to create the software,
Testing: Check for and fix any problems or bugs in the softwaie.
Deployment: Release the software for users to use.
eens
7* Maintenance: Make updates and fix any issues that come up after the
software is in use.
Benefits and Limitations
. Benefits:
1. Simple and Easy to Understand: The Waterfall Model is easy to follow
because it has clear, distinct phases
2. Sequential Process: Each phase is completed one at a time, which makes it
easier to manage and track progress.
3. Suitable for Small Projects: Works well for projects with clear, fixed
requirements where changes are unlikely.
. Limitations:
1. Inflexibility: Once a phase is completed, going back to make changes is
difficult and costly.
2. Not Ideal for Complex Projects: For projects with evolving requirements or
complex designs, this model can be challenging to use effectively.
4, Risk and Uncertainty: The model assumes that all requirements are known
from the start, which can be risky if new needs or issues arise later in the
process.
Waterfall
(Plan Briven)
Project Timeline
Figure 1,2: Waterfall Model
1.1.1.1 Agile Methodology
Agile Methodology is flexible and adaptive approach to software development. Unlike
the Waterfall Model, which follows a strict sequence of steps. Agile focuses on delivering
small, functional parts of the software quickly and adapting to changes as the project
progresses, The main idea is to work in short cycles, called iterations or sprints, which<
help teams deliver parts of the software rapidly and gather feedback early as shown in
Figure 1.3, Agile methods include practices such as:
Continuous Integration: Regularly merging code changes into a central
repository to detect and fixissues early.
Test-Driven Development: Writing tests before writing the code to ensure the
software works as expected
Pair Programming: Two developers work together at one workstation, with one
writing code and the other reviewing tin real-time.
o
S,
Figure 1.3: Agile Methodology
Benefits and Limitations
Benefits:
1.
High Flexibility: Agile allows for changes in requirements even after
development has started, making it easier to adapt to new needs or feedback.
2. Improved Customer Satisfaction: Regular updates and frequent delivery of
working software mean that customers can see progress and provide feedback
more often.
Limitations:
1. Scaling Challenges: Managing large projects with many teams can be difficult,
asit requires careful coordination and communication.
2. Stakeholder Involvement: Agile. requires active participation from all
stakeholders, which can be challenging if some are unavailable or not fully
engaged.
3. Less Predictable: Since Agile projects evolve through feedback and changes, it
can be harder to predict the exact timeline and scope of the final product.
91.1.4.1 Other Methodologies:
|, Scrum
Scrum is an agile framework widely used for managing and completing complex
software projects. It promotes iterative progress, collaboration, and flexibility, making it
well-suited for dynamic environments where requirements can change frequently, The
framework is built around a set of roles, events, and artifacts designed to create a
structured yet adaptable approach to project management.
Key Components of Scrum:
© Roles: The primary roles in Scrum are the Praduct Owner, Scrum Master, and
Development Team. The Product Owner defines the product backlog and
ensures that the team is working on the highest-priority items. The Serum
Master facilitatés the process, removes obstacles, and ensures that the team
follows Scrum practices, The Development Team, consisting of cross-functional
members, is. responsible for delivering the product increments.
+ Events: Scrum employs a series of events to ensure regular progress and review.
These include Sprints (time-boxed iterations), Sprint Planning, Daily Standups,
Sprint Reviews, and Sprint Retrospectives.
* Artifacts: Key artifacts in Scrum are the Product Backlog (a prioritized list of
features and requirements), Sprint Backlog (a list of tasks to be completed ina
Sprint), and Increment (the working praduct that is the result of the current
Sprint).
Suitable for Scrum: Scrum is particularly suitable for software projects that require
frequent updates and have evolving requirements, such as:
* Mobile Applications: Mobile app development often invalves continuous
feedback and rapid iterations to meet user needs and stay competitive. Scrum’s
iterative nature allows for quick adjustments based on user feedback and market
changes.
* Web Development: For web applications that require regular feature updates.
and improvements. Scrum facilitates a responsive development process that can
quickly adapt to new requirements and user feedback.
Not Suitable for Scrum: Scrum may not be ideal for projects with well-defined
requirements and little expected change, such as:
*. Embedded Systems: Development of embedded systems, which often involves
hardware integration and stringent requiatory requirements, may benefit froma
more traditional, linear approach rather than the iterative nature of Scrum,
* Safety-Critical Software: Projects such as medical software or aerospace
systems, where thorough documentation and extensive: validation are crucial,
might notalign well with the flexible and iterative nature of Scrum.Ks oa
the Serum process flow, highlighting the key components and their interactions
SCRUM LIFECYCLE
‘ Figure 1.4; Scrum Lifecycle
ii, Lean
Lean Software Development is an iterative approach to software development that
emphasizes efficiency, eliminating waste, and delivering high-quality products quickly.
Derived from Lean manufacturing principles. Lean Software Development focuses on
delivering value to the customer by optimizing the flow of work and minimizing
unnecessary activities.
inciples of Lean Software Development:
Eliminate Waste: Identify and remove activities that do not add value to the
customer.
2. Amplify Learning: Foster an environment of continuous improvement and
learning.
3. Decide as Late as Possible: Make decisions based on the latest possible
information to reduce uncertainty.
4. Deliver as Fast as Possible: Prioritize rapid delivery of small, incremental feat
5. Empower the Team: Give teams the authority and responsibility to make
decisionsand solve problems.
6. Build Integrity In: Ensure quality is maintained throughout the development
process.
7. See the Whole: Consider the entire system and its context to optimize the
overall flow of work.
1OOOR
we
Biminato Amplify“ Dacideos Delivers Empower ‘Bui ‘Optimize:
teaming Leite-05 Fomas the Team =—integrisyin) the whole
Possible Possible
Figure 1.5: Lean Software Development Model
Suitable for Lean: Lean Software Development is particularly suitable for projects that
require rapid delivery and frequent iterations, such as startup software, mobile
applications, and web-based services. For instance, a startup developing anew mobile
app would benefit fram Lean principles by quickly iterating on user feedback and
delivering updates that add value
Not Suitable for Lean: Lean Software Development might not be ideal for projects that
require extensive upfront planning and are highly complex or regulated, such as large-
scale enterprise systems, embedded systems, or safety-critical applications. For
example, developing software for an aviation control system would demand rigorous
documentation, extensive testing, and regulatory compliance, which may not align welll
with the iterative nature of Lean.
1.1.1.1 DevOps
DevOps is a set of practices that combines software development (Dev) and IT
‘operations (Ops) to enhance collaboration, efficiency, and agility in delivering software
products and services as shown in Figure 1.6. The primary goal af DevOps is to shorten
the development lifecycle, improve software quality, and provide continuous delivery
with high reliability.
Why DevOps Should Be Practiced: DevOps should be practiced because it brings
numerous benefits to the software develapment and delivery process:
1. Improved Collaboration: DevOps fosters a culture of collaboration between
development and operations teams, breaking down silosand ensuring thatboth
teams work towards common goals.
2. Faster Time-to-Market: By automating processes and enabling continuous=
integration and continuous delivery (CI/CD), DevOps allows teams to deliver
software updates and new features more rapidly,
Enhanced Quality: Continuous testing and monitoring in DevOps help identify
and address issues early in the development cycle, resulting in higher quality
software.
4. Increased Efficiency: Automation of repetitive tasks reduces manual effort and
the risk of human error, leading to more efficient workflows.
ae
fo Sher )
Figure 1.6: DevOps Methodology
Suitable for DevOps: DevOps is ideal for web and mobile apps, and cloud services
Where fast development and scaling are crucial. For example, Amazon's e-commerce
platform uses DevOps to continuously release new features and updates.
Not Suitable for DevOps: DevOps may be less suitable for highly regulated or
hardware-dependent projects. For instance, software for medical devices needs
rigorous testing and compliance, which may not fit with DevOps's rapid pace.
The term Waterfall was first introduced by Dr. Winston W. Royce in 1970, but he did not
advocate for its use without iteration.
1.5 Project Planning and Management
Planning a software projectis like planning a trip. You need to know where you're going,
how long itwill take, and how much it will cost.
The 5 Phases of a Project Management Plan
o__e___e—_o——
slmlelale
13
»1.4.1 Comprehensive Project Planning
Comprehensive project planning involves thinking about all the details of your project
before you start. includes understanding what needs to be done, who will do it, and
how itwill be done,
Some of the largest software development companies in the world
OID YOUN... ereworth bitfigns of doltarst Forexample, as 0f2023, Microsoft, one of
(aa the leading softwere giants, has a market capitalization exceeding $2.
& trillion. This immense value highlights the significant impact and
economicimportance of software development in today's digital age,
1.4.2 Setting Project Timelines
Setting project timelines means deciding howlong each partof the project will take. This
helps keep the project on track and ensuresitgets done on time.
Example: If you're building a website, you might set a timeline for designing the site,
another for writing the content, and another for testing everything.
1.4.3 Estimating Costs
Estimating the cost of a software project is a critical step in project planning and
management. Itinvolves predicting the total expenses required to complete the project
successfully. Accurate cost estimation helps in budgeting, resource allocation, and
setting realistic expectations. Here, we will explore the key factors involved in estimating
software project costs and provide an example to illustrate the process.
Key Factors in Cost Estimation:
*® Development Team: The cost depends on the number of developers, their
expertise, and their hourly rates, Teams with specialized skills may charge
higher rates.
* Technology Stack: The choice of technology, programming languages, and
tools can affect the cost. Some technalogies require more resources or
specialized knowledge:
+ Project Duration: Longer projects generally incur higher costs due to
prolonged resource engagement and potential changes in scope,
* Risk Management: Identifying potential risks and their mitigation strategies
can add to the overall cost. Cantingency funds are often included to address
unforeseen issues.
* Quality Assurance: Costs associated with testing, bug fixing, and ensuring
the software meets quality standards are also part of the estimation.
Example: Let's consider a scenario where a company in Pakistan wants to develap a
mobile application for online shopping.
© Scope: The app will include user registration, product listings, shopping cart,
paymentintegration, and order tracking,
14Development Team: The project requires a team of 1 project manager, 2
frontend developers, 2 backend developers, 1 UI/UX designer, and 2 QA testers.
Technology Stack: The app will be developed using React Native for cross-
platform compatibility, Nodejs for the backend, and MongoD8 for the
database.
Project Duration: The estimated duration is 6 months.
Operational Costs: Costs include cloud hosting, development tools, and
software licenses.
Risk Management: Potential risks include scope changes and technology
integration issues, with a contingency fund of 10% of total cost.
Quality Assurance: Includes comprehensive testing phases to ensure
functionality and performance.
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.—o———~—~_~S EEE
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 qualitystandards.
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 moreattention,
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 toadjuststravegies as necessary.
Example: A project is using a new, untested technology. The risk is that the technology
may notworkas expected, causing delays and additional costs,
Mitigation Strategy: Conducta 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 asmoother project execution.
1.1.2. Quality Assurance
Quality assurance ensuires that a project meets’ set standards and works correctly: It
involves methods such as testing, reviewing code, getting feedback fronv 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 mariage the system. Diagrams, like Unified Modeting
Language (UML) diagrams, are widely used to illustrate various components, their
16
3.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.
DID YOU!) UML was created by three software engineers: Grady Booch, James
Rumbaugh, and Ivar Jacobson. They are often called the “Three
Amigos" of UML,
1.1.1 Types of UML Diagrams
In this section, we will discuss four types of the UML diagrams that are give below.
1.1.1.1 Use Case Diagrams
Use Case Diagrams are a fundamental component in the Unified Modeling Language
(UML) used to depict the various ways in which users, referred to as actors, interact with a
system. These diagrams provide a visual representation of the system's functionality
from the user's perspective, helping to identify the requirements and the interactions
between the users and the system.
Definition and Purpose:
Ause case is a description of a set of interactions between a user (actor) and a system to
achieve a specific goal. Use cases are identified based on the functionalities that the
system must support to meet the user's needs. Each use case represents a complete
workflow from the user's perspective, detailing the steps involved in accomplishing a
particulartask.
Use Case Diagrams are used for several purposes:
1. Capturing Functional Requirements: They help in identifying and
documenting the functional requirements of the system.
2. Understanding User Interactions: They illustrate how different users will
interact with the system
3. Planning and Testing: They aid in planning the development process and in
designing test cases for validating system functionalities.
Identifying Use Cases:
The process of identifying use cases involves several steps:
1, Identify Actors: Determine the different types of users who will interact with the
system. Actors can be human users or other systems.
2. Define Goals: For each actor, identify their goals or what they need to
accomplish using the system.
173. Outline Interactions: Describe the interactions between the actors and the
system to achieve these goals. Each interaction that results in a significant
outcome isa potential use case.
4. Validate Use Cases: Review the identified use cases with stakeholders to ensure
they accurately capture the required functionalities and interactions
Simple Use case diagram
Figure 1.9: Exa
3. Outline Interactions: Describe the interactions between the actors and the
system to achieve these goals. Each interaction that results in a significant
outcome is a potential use case.
4. Validate Use Cases: Review the identified use cases with stakeholders to ensure
they accurately capture the required functionalities and interactions.
iagram for a'Library Syster
Class Activity
Objective: Learn to identify actors and use cases from a given statement
describing asystem.
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
—_—_———————.4Class 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
© Administrator
o Delivery Personnel
=» Use Cases:
Browse Products
Add Items ta Cart
Make Purchase
Manage Product Listings
Process Orders
Handle Customer Inquiries
Update Delivery Status.
1.1.4\1 What isa Class Diagram?
‘A class diagram is like a map that shows how things aré 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 aré related.
Example:
Inthe example of s organizing yourroom:
. 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 ina
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 @TayBox’ for
toys, a ‘BookBox' for books, and.a ‘ClothesBox' for clothes, representing
distinct instances of the general ‘Box’ class.
So, aclass diagram is simply away to organize and show how different parts of a system.
(like your roam) work together, making it easier to understand everything ata glance as
show in Figure 1.10. +0
860600000Room
-name: String
-sice: String
Z_
Box
slabel: String
scomtents: Siring
BookBox ClothesBox
N books: List clothes: List
Figure 1.10: Class Diagram for Organizing Your Roorn
1.1.1.1 Sequence Diagrams
Sequence Diagrams show how objects ina system interact with each other ina particular
sequence. They help in understanding the flow of messages between objects over time.
Interactions:
* open(): User opens each box.
* put toys/books/clothes insi
boxes.
© close(): User closes each box.
: User puts the respective items into the
Books Box
cloxeO
Figure 1.11: Sequence diagram of the user organizing items into labeled boxes1.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’.
Figure 1.12: Activity Diagram with Decision and Connector Symbol
Above activity diagram shows haw 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,—$<$—$———————— |
1.6 Introduction to Design Patterns
Design patterns are a fundamental concept in software development. providing proven
solutions te common problems that arise during software development. They serve as
blueprints ar templates that can be adapted to solve various design challenges, making
the development pracess more efficient and consistent.
The cancept of design patterns was popularized by the book ‘Design
~ Patterns: Elements of Reusable Object-Oriented Software’ by Erich
Gamma, Richard Helm, Ralph Johnson, and John Vlissides; also known
as the “Gang of Four".
1.6.1 Commonly Used Design Patterns
‘There are numerous design patterns, but some are more commonly used due to their
Versatility and effectiveness in solving awide range of problems. Below are some of the
most widely recognized design patterns:
1.6.1.1 Singleton Pattern
The Singleton Design Pattern isa way to'make sure that a specific object of resource is
created only once ina program and reused whenever needed. Think of it like having just
‘one key to a special room, and no matter whe needs to getinta the room, theyall haveto
use thatsamekey. Nomew keys are made, and everyone shares that one key.
1.6.1.2 Factory Pattern
The Factory Design Pattern is like having a special workshop that knows how to create
different products, but you don't need to worry about the details of how those products
are made. Instead, you just tell the factory what you need, and it gives you the finished
product.
1.6.1.3 Observer Pattern
The Observer Design Pattern is like having 2 group of people who are interested in
getting updates from one particular source. Whenever something important happens,
the source automatically notifies all the interested people. It's a way to keep things in
sync withauteveryone constantly checking for updates.
1.6.1.4 Strategy Pattern
The Strategy Design Pattern is like having a toalbox full of different tools, each designed
for aspecificjob. When you face a problem, you can pick the fight tool
from the box based on the task at hand, In other words, you have “multiple ways” to.
solve a problem, and you can switch between them easily without changing much else,1,6.2 Applications of Design Patterns in Software Design
Design patterns are widely used in software develapment 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.
Many popular software frameworks and libraries are built using
O10 a. design patterns, For example,. the Model-View-Controller: (MVC)
ea. pattern is used in web development frameworks like Ruby on Rails
and Angular.
1.7 Software Debugging and Testing
Software debugging and testing are critical stages in the software development process
that ensure the quality and reliability of a software product. Effective debugging and
testing help developers to confifm that the software meets the required specifications,
functions as intended, andis free of critical errors,
1.7.1 Debugging
Debugging is the process of finding and fixing bugs or errors in a software. Software
debugging and testing are essential parts of software development. They ensure that
the software works correctly and meets the user's requirements,
Bugs are errors or mistakes in the software that cause it to behave unexpectedly.
Identifying bugs involves observing the software's behavior and finding the source of
the problem. Once identified, solving bugs requires making changes to the code to
correctthe error.
o1D YO Debugging was named after am incident in 1947 when a real bug (a
moth) was foundin a computer!
Tools and Best Practices
There are various tools and best practices for debugging, including:
+ Debuggers: Software tools that help programmers find bugs by allowing
them to step through code, inspect variables, and monitor program
execution,
* Print Statements: Adding print statements in the code to display the values
of variables at different paints in the program:* Code Reviews: Having other developers review your cade to spot potential
errors.
L741 Testing
Testing is the process of evaluating the software to ensure it meets the requitements and.
works as expected. The testing process typically follows a hierarchy that begins with
smaller components and gradually progresses to. the entire system, including user
acceptance. The main types of testing in this hierarchy are given below.
1.7.2.1 Unit Testing
Unit Testing is the first level of testing, where individual components or modules of the
software are tested in isolation, Each "Unit" is a'small, testable part of the software, such
as a function or methad. The primary goal of unit testing is to verify that each
component works correctly according to its design and performs as expected.
4.7.2.2 Integration Testing
After unit testing, Integration Testing is performed to evaluate the interaction between
different components. or modules. While unit testing focuses on isolated units,
integration testing ensures that these units work together correctly when combined.
This type of testing checks for interface errors, data flow between modules, and other
integration-related issues. It helps identify problems that may not arise during unit
testing, such as mismatches in module communication or data handling.
1.7.2.3 System
System Testing is a higher level of testing where the entire software system is tested asa
whole. At this stage, the software is treated as a complete entity, and testers evaluate its
overall functionality, performance, security, and compliance with specified
requirements, System testing involves testing the software in an environment that
closely resembles the production environment to ensure that it functions correctly
under real-world conditions. This level of testing helps identify defects that may arise
from the interaction of various system components and verifies that the software meets
its intended purpose,
1.7.2.4 Acceptance Testing
Acceptance Testing is the final level of testing conducted to determine whether the
software is ready for rélease. Itis often performed by the end-users or clients to ensure
that the software meets their expectations and requirements. Acceptance testing can be:
formal or informal and typically includes scenarios that mimic real-world usage to
validate the software's usability, reliability, and performance.
aRequirement gathefing is. similar to planning a big event, like a
OID YOU. wedding? Justias you need to know the preferences of the brideand
(ANCA) 1S groom, developers: need to know what the Users want from the
software.
4.7.2.2 Integration Testing
After unit testing, Integration Testing is performed to evaluate the interaction between
different components or modules. While unit testing focuses on isolated units,
integration testing ensures: that these units work together correctly when combined.
This type of testing checks for interface errors, data flow between madules, and other
integration-related issues. It helps identify problems that may not arise during unit
testing, suchas mismnatches in module communication or data handling,
1.7.2.3 System Testing
System Testing is a higher level of testing where the entire software system is tested asa
wholes At this stage, the software is treated asa complete entity, and testers evaluate its
overall functionality, performance, security, and compliance with specified
requirements. System testing involves testing the software in an environment that
closely resembles the production environment to ensure that it functions correctly
under real-world conditions. This level of testing helps identify defects that may atise
from the interaction of various system components and verifies that the software meets
its intended purpose,
1.7.2,4 Acceptance Testing
Acceptance Testing is the final level of testing conducted to determine whether the
software is ready for release: It is often performed by the end-users or clients to ensure
that the software meets their expectations and requirements. Acceptance testing can be
formal or informal and typically includes scenarios that mimic real-world usage to
validate the software's usabillty, reliability, and performance.
DID YOU.” acceptance testing is sometimes called User Acceptance Testing
KNOW? (UAT) because it is often done by the end-users of the software.
1.8 Software Development Tools
Software. development tools are essential for creating, testing, and maintaining
software applications.
These tools help developers writé code, find and fix errors, and manage software
projects effectively.
1.8.1 Definitions and Usage
Software development taols are programs orapplications that assist in various stages of
software creation. They are used to write, edit, test, debug, and manage code, ensuring
2re =
that software functions correctly and efficiently.
1.8.2 Language Editors
Language editors, also known as code editors, are tools that help developers write and
edit code in different programming languages. The purpose of language editors is to
provide a user-friendly interface for writing code. Examples include:
* Notepad++: A simple yet powerful code editor,
* Sublime Text: Known for its speed and ease of use.
* VS Code: A popular editor with many extensions.
1.8.3 Translators
Translators are tools that convert code written in one programming language into
another language that the computer can understand. Translators convert high-level
programming languages (like Python) into machine language (binary code) that
computers can execute.
* Interpreters: Translate code line-by-line (e.g., Python interpreter).
«Compilers: Translate the entire code at once (e.g., GCC for C/C++).
1,8.4 Compilers
Compilers are a type of translator that converts entire programs from high-level
languages into machine code before execution. The purpose of compilers is to optimize
and convert code into efficient machine code. Examples include:
GCC: GNU Compiler Collection for C and C++. Javae: Compiler for Java programs.
1.8.5 Debuggers
Debuggers are tools that help developers find and fix errors (bugs) in their code, The
purpose of debuggers is to allow developers to test their code and identify where emors
occur. Examples include:
GDB: GNU Debugger for C/C++
Visual Studio Debugger: Integrated with Visual Studio IDE.
1.8.6 Integrated Development Environments (IDEs)
IDEs are comprehensive software suites that provide all the tools needed for software
development in one place. IDE integrate various development tools like editors,
compilers, debuggers, and version control systems to streamline the development
process. An IDE offers a unified interface where developers can write, test, and debug
their code efficiently.
‘Common IDEs
a Eclipse: Widely used for Java development.
. Visual Studio: Popular for.NET and C++ development.
. PyCharm: Preferred for Python development.
261.8.7 Online and Offline Computing Platforms
These platforms provide environments where developers can write, run, and test their
code.
* Online Platforms: Cloud-based platforms accessible via the internet (e.g.,
Repl.it, Gitpod).
* Offline Platforms: Local development environments on a computer (€.9,,
local installations of IDEs).
1.8.8 Source Code Repositaries
Source code repositories are platforms where developers can store, manage, and track
changes to their code. Repositories help in version contral, allowing multiple developers
to work on the same project without conflicts. Repositories keep track of code changes
and maintain a history of all modifications.
© GitHub: Popular platform for open-source projects.
*«__Bitbucket: Used for both private and public repositories.
Summary
in this chapter, you were introduced to the essential aspects of software development,
rom the fundamental concepts and key terminology to the detailed stages of th
oftware Development Life Cycle (SDLC). You explored different software development
thodologies, including the Waterfall model and Agile methodology, and learn
‘to plan and manage a software project effectively. The chapter also covered qualit
ssurance techniques, the use of UML for graphical representation, and the importancs
design patterns in software design. Finally, you were introduced to debuggin
hniques, testing strategies, and various software development tools that aid in th
ficient development of high-quality software products.
Q.1: Multiple Choice Questions
1. Whats the primary purpose of the Software Development Life Cycle (SDLC)?
a) To design websites
b) To deliver high-quality software within time and cost estimates
©) To manage database systems
d) —Tocreate hardware components
2. Which type of requirement specifies how the system should perform?
a) Functional Requirements
b) — Non-Functional Requirements
©) Technical Requirements
d) Operational Requirements3. Inthe context of SDLC, what is the role ofa framework?
a) To write code from scratch
b) To provide a structured foundation with predefined companents and
architectures
oO To manage hardware
d) To perform manual testing
Which software development model Involves working in short cycles or spirits?
a) Waterfall Model
b). Agile Methodology
Q Lean Software Development
d) Scrum
Which role is responsible for removing obstacles and facilitating Scrum practices?
a) Product Owner
b) Scrum Master
oO Development Team
d) Project Manager
». Whichof the following is nota benefit of DevOps?
ab Improved collaboration
b) Enhanced quality
Q Increased project scope creep
d) Faster time-to-market
7. What isa crucial aspect of comprehensive project planning?
a) _ Understanding the project’ scope and tasks
b) Deciding the project's colour scheme
o Hiring alargedevelopmentteam
d) Ignoring potential risks
|. Which factor does NOT influence thecost estimation ofa software project?
a) Scope of the project
by Technology stack
oO Numberofmeetings held
d) Operational costs
).'Whatis the purpose ofa contingency fund in cost estimation?
a) Tocoverunexpected costs
b) To pay for marketing expenses
¢ To hire additional developers
d)— Topurchase new hardware
10. Which of the following isa purpose of Use Case Diagrams?
a) —_ Todocumentthe system's architecture.
28
-
w
2
2
ob) Toidentify and document the system's functional requirements.
©) —_Tajllustrate the databaseschema.
gd) Todefine the system'suser interface design.
Questions
Differentiate between functional and non-functional requirements.
2. Explain why the testing phase is important in the Software Development Life
Cycle (SDLC), and provide two reasons for its significance.
3. Illustrate the concept of continuous integration in Agile Methodology and
discuss its importance in software development,
4. Identify the key components of the Scrum framework and analyze how each
contributes to effective project management.
5. Evaluate the main steps involved in risk assessment and management, and
assess their importancein a software project.
6. Explain the purpose of a Use Case Diagram in software develapment.
7. Compare and contrast a Sequence Diagram with an Activity Diagram,
highlighting the key differences.
8. Describe the Factory Pattern and explain how it differs from directly. creating
objects, with anexample.
‘Long Questions
1. Design a flowchart fora user registration process in a software application,
Outline its key steps,
2, Imagine you are managing a project to develop a-simple mobile application:
Describe how you would use the Agile Methadolagy to handle this project.
3. You are working oma project that requires extensive documentation and has
very specific regulatory requirements. Discuss why the Scrum methodology
might not be suitable forthis project and suggest an alternative methodology.
4. Consider an online banking system. Create a Use Case Diagram to show the
interactions between customers, bank staff, and the system.
5. You are developing a food delivery application, Create a Sequence Diagram to
show the process of placing an order, from the customer selecting items to the
delivery of the order.
6. Discuss the importance of software development tools in the software
development process.
Explain the role of language editots, translators, and debuggers in creating and
maintaining software.
Provide examples of each taol and describe haw they contribute to the
efficiency and accuracy of software development.
a)
b)
2Python Programming
Biron c ees
By the endof this chapter, students will be able to:
'* Understand basic programming cancepts 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 contro! 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.Intreduction
Welcome ta 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(CL!) applications.
2.1 Introduction to Python Programmi
Python is a widely-used high-tevel programming language celelsrated 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 ar developing sophisticated software, Python's
user-friendly nature helps you getstarted quickly and efficiently.
(| Ol
2.1.1 Understanding Basic Programming Concepts
Computer programming is the process of creating a set of instructions that tell a
computer how to perform a task. These instructions are written in. a programming,
language that the computer can understand and execute. Think of computer
programming like giving directions to a friend on how to reach your house. You need to
be clear and precise so your friend doesn't get last. Similarly, when we write programs,
we give clear and precise instructions to the computer to complete specific tasks,
2.1.1.1 Programming Basics
Computerprogramming involves the following basic steps to writea program.
1. Write Code: Create a set of instructions in.a programming language.
2. Compile/Interpret: Translate the code into a form that the computer can
understand.
3. Execute: Run the code to perform the task.
4. Output: Display the results or perform actions based an the code.
2.1.1.2 Setting Up Python Development Environment
The development environment refers to the process of preparing a computer to write,
run, and debug Python code effectively. This involves installing and configuring the
necessary software; tools, and libraries that make development smoother and more
4
ID YOUN. Python is named after the British comedy series "Monty Python's
Flying Circus.” notthe snake!> |
efficient. We'can download and install Python from https: //www. pythan, org/, When
starting with Python programming, choosing a good Integrated Development
Environment (IDE) can help make'coding easier,
2.2 Basic Python Syntax and Structure
The following Python program demonstrates the simplicity and readability of the
language:
print(“As ~ Salaam-Alaikum, College Students!")
linthis example, the’ print function is utilized to output the message enclosed in double
quotation marks. This illustrates Python's straightforward syntax, where functions like
prititare used to petform actions such as displaying text.
Python Comments
Lines that are not executed by the Python interpreten They are used to provide
explanations or notes for the code. Single-line comments start with the # symbol while
multi-line comments can be created using triple quotes ("") at the beginning and the end
as shown below,
# This is a single - Line comment
print( "K2is the second-highest mauntain in the world")
This ts amu
t can span mu
print ("Edhi Foundation operates the world’s largest volunteer ambulance
network." )
ine comment,
itiple lines.
2.2.1 Variables, Data Types and 1/0
2.2.1.1 Variable
A variable in programming functions as a storage container within a computer's
memory, allowing for the storage of data that can be retrieved and manipulated laterin
the code. In the example below, the variable age is utilized to hold numerical data. The
value ofa variable can change throughout the execution of a program, whichis why itis
referred toasa “variable”:print (age ="As - Suluam-Alnikum , dear students {)
age=71
print "Quaid-+Azam lived for", age, "Yemes")
age =60
print (-"Alkmaitgbal tived for", age, "years")
This example illustrates haw the variable “age” is assigned different values to represent
the ages of Quaid-i-Azam Muhammad Ali Jinnah and Allama Iqbal, which are then
printed as part of the output.
2.2.4.2 Variable Naming Rules in Python
Variable names in Python must adhere to the following rules:
* The name must begin with a letter (a-z, A-Z) or an underscore (_).
* Subsequent characters can include letters, digits (0-9), or underscores (_).
* Variable names-are case-sensitive; meaning age and Age are considered two
different variables.
* Python's reserved keywords, such as for, while, if, etc., cannot be used as
variable names.
2.2.1.3 Creating Different Types of Variables
In Python, you can create variables of different types ta store various kinds of data, Here
aresome commen types of variables;
* Integer (int): Stores whole numbers. Example: age = 17
* Floating-point (float): Stores decimal numbers. Example: price = 19.99
* String (str): Stores text. Example: name = “All”
* Boolean (bool): Stores True or False. Examp
2.2.4.4 Input and Output Operations
Input and output operations allow you to interact with the user. You can ask the user to
enterdata (input) and display information to theuser (output).
* Input: Use the input () function to get user input. The input (} function displays a
33messageon the screen and waits for the user ta type something and press Enter.
The text entered by the userjs then stored ina variable. Forexample:
name = input(“Enter your name: *)
This line of code asks the user to enter their name and stores it in the variable name.
* Output: Use the print 0 function to display information on the screen. The print
() function takes one or more arguments and displays them. For example:
print” As- Salaam - Alaikum, "+ name +"!")
This line of codedisplays'a greeting message that includes the user's name.
2.2.1.8 Handling Integer and Float Inputs
To handle numeric inputs, you typically use the int( or float() functions to convert input
strings to integers or floating-point numbers, respectively.
Integer Inputs
# Bxamp: Randling sriteger
user_oge=ini(imput(“Enteryourage:"))
Brint("Yourage is:".tiser_ age)
Float Inputs
# xample: Handling float: input
user_height = float(input("Enter your height in meters: "))
print("Your heightis”, user_height,"meter")
2.3 Operators and Expressions
Operators aresymbols that perform operations on variables and values. An expressianis
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
operationsin Python.
4 Define variables
a=10b=3
& Perform all arith
and print results
printla,"+",b,"=“a+bi # Outps
printa."*b,"=",a"h) # outpu
printia,"/'\b,"=",a7b)
on these numeric wariabjles:rina, 77", 6,”
yutput tb
Atutorial on Pythons available at g
https: //does python.org/3/tutorial/
2.3.2 Comparison Operators
Comparison operators are used to compare two values or expressions, They determine
the relational lagic between them, such as equality, inequality, greater than, less than,
and soon, These operatars return a boolean value (True or False) based on the
comparison result. Here's a Python program that demonstrates the usage of all
comparison operators.
# Define variables
xy ys 18s &
@ Greater than
print, "9", y, "", 23 y) # Output: 19 > 5 + True
# Less, than
priat(k. "44. ys Met. x ey) # Mutper: 10 < S © Flee
# Baual) co
pring (x, =e", y, "en, emmy) 8 Ouepur! 10 = 6 © Paleo
# Net equal to
print(s, “He". ys *
@ Groater than’ or
prant(x, t8*,
# Loss than or
print (x, "<8",
em ds y) @ Output: 10 4> 6 © True
al! re
x >" 9) # Outpur: 10 = 5 = True
pox <2 y) # Output: 10 <= 5 = Faiae
The above code demonstrates Python's comparison operators by defining two
variables, xand y, and comparing them using various operators like >, <,==,!=,>=,and
<=,
“in programming, the hard part isn't solving problems, but-deciding what problems to
solve.”: Paul Graham
"Programming isn'tabout whatyou know; it’s about what you can figure out.
hris Pine————~EeeyErEF|A
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 compaund assignment operators like +=, and
/=, which’ combine arithmetic operations with assignment.
Define initial values
a io
bes
© Aasignnent
assignment © a; print(Ta ="; assignment) # Durpot: a = 10
Addition asniganont
+= b; print(*s efter addition «", a) Butput: a = 15
Subtraction ai nt
tuperaction =
agnzent
obi pe ez multiplicatiak +", a) Output: a + $0
Division assignrent
Cre after division +". a)e Output: a = 10.0
ygpsent
Mie b; print("e after floor division =", a) Output: a 2.0
Modulus assigament
X= b; prine(*a after sodsiue =", ade Gktpory a = 2/0
Exponentiation amet gnaent
b: pEine("s after exponentiation =", aJwOurput: a 32.0
Above code illustrates the use of assignment operators in Python. The code comments
show the output of each operation,
1.1.3, Legical Operators
Logical operators are used to combine multiple conditions or expressions Ina program.
The most common logical operators are and, of, and not. They are used to perform
logical operations and return Boolean walues based on the evaluation of the expressions
involved.
“# Define variables
x=True
y= False
# Logical AND
lagical_and=xand y
print(x, "and", y,"="" logical_and) # Output: Trucund False=False
dLogical OR.
lagical_or=xory
print(x, "or" .y," =", logical_or) # Output: Trueand False = True
36
eee
as Ousput: a= 10
Per ep ep =e =e wre# Logical NOT
logical_nat_x = notx
print(’not", x, , logical_not_x) # Oitputriot Truc=False
logical_not_y=noty
print(‘not”, y, "=", legical_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
onthem. The codealso includes comments with the output of each logical operation.
2.3.5 Expressions
An expression is a combination of variables, operators, and values that producesa result.
For example, 3 + 4 isan expression that results in 7. More complex expressions can use
parentheses O to control the arder of operations. For exampie:
result=(344)"2 #resultis 14
Class Activity
Write a program te 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)
* heightis in meters (m)
2.3.6 Operator Precedence in Python
Operator precedence determines the order in which operations are performed in an
expression. In Python as well as. in Mathematics, certain operators have higher
precedence and are evaluated before others. Understanding this helps ensure that your
calculations are done correctly.
* Parentheses "()": Highest precedence. Operations inside parentheses are performed
first. (3+ 2) *4 evaluates ta 20.
+ Exponentiation: Performs power operations next.
+ 2'evaluatesto8.
* Multiplication ‘*’, Division '/', and Modulus '%': These operations come next. 4°3
evaluatesto 12, 10/2evaluates to 5.0 ant 1%3 evaluates 2.2 2
+ Addition '+' and Subtraction
multiplication and division.
* 5+ 2evaluates to7,and 10-4 evaluates to6.
* — Exarnple: Consider the expression 3 + 2*S. The multiplication is performed before
theaddition,so: 34+2*5 =3+10=13
“Glass Activity
Compute the following expressions and compare results with your class
fellows and class teacher.
1. 10+*3922-5/5
2, (104+3)*(@@" (2-1/5
Translate the fallowing in Python's syntax
1 5 43x4-72°41
2 10x (2+3)-48: 245
These have lower precedence compared to
olD oe w- Using parentheses can help clarify complex expressions and ensure
= the operations are performed in the desired arder.
2.4 Control Structures
In programming, we often need to control the flow of our program based on different
conditions or repeat certain actions multiple times. This is where contro! structures
come into play. Thefe are two main types of control structures, Decision making and
Looping:
2.4.1 Decision Making
Decision making in programming allows the program to choose different actions based
onconditions. This is similar to how we make decisions in real life. Python provide variety
of conditional statements to implement decision making. Below find the detailed
implementation of python conditional statements.
2.4.1.1 if Statement
The if statement lets us make decisions based on conditions. If the condition is true, it
runss block of code.
# Syntax of if statement if condition:
If condition:
# code to run if the-candition is true
Example: Ifthe temperature isabove 30 degrees, we printa message.
temperature = 35
iftemperature > 30:
print("It's ahor day")2.4.1.2 if-else Statement
The if-else statement allows us to execute one block of cade if a condition is true and
another block ifthe condition is false.
Syntax of if-else statement:if condition:
IFcondition;
# code to run if the condition is trueelse =
else:
# code torun if the condition is false
Example: [temperamre = 15
‘if temperature > 30;
rina "It's a hot day")
else:
Prini("I’s nat a hor day")
2.4.1.3 Short Hand if-else Statement,
Putten also allows a short-hand if-else statement that can be written ina single line.
Syntax of short hand if-else statement
action_if_true ifcondition elseaction_if_faise
temperature = 15
print(“tt's-a hot day")
if temperature'> 30 else
print(’It’s nota hot day")
Explanation: This is the same as the previous example but written in a more compact
form. The output of the code depends on the value stored in the variable “temperature”,
it prints “It's a hot day” if the value is greater than 30, otherwise it prints “It's nota hat
2.4.1.3 if-vii-else Statement
The if-elif-else statement allows us to check multiple conditions and execute different
blocks of code for each condition.
# Syntax of if-elif-else statement
if condition:
# code to run if/condition! is true
elif condition:
# code to run if:condition2 is true
else:
#icode te tun if none of the conditions are true
Example: sweather = “cloudy” # The output depends on the value stored in the variable”
weather®
if weather == "sunny":
print(Wear siinglasses")
elif weather == "rainy":
print('Take an umbrella”)
else:
print(“Enjoy your day!")
Explanation: In this example, the code checks multiple weather conditions. If the
weather is “sunny’, the program prints "Wear sunglasses”. If the weather is “rainy”, the
Program prints “Take an umbrella”. If the weather is neither “sunny” nor ‘rainy’, the
program prints "Enjoy yourday!”.
Sometimes, we need to check multiple conditions inside another condition. This is called
nesting,
# Syntax of nested if statement
ifcondition1:
ifcondition2:
# code to run if both conditionl and condition2 are
true
else:
# code to. run if condition] is true but condition? is
false
else:
# code torn if condition] is false
Example: If the weather is rainy and the temperature is below 15 degrees, we wear a
raincoat, Ifitis only rainy, we take an umbrella, If the weather is not rainy, we just enjoy
theday.
weather = “rainy”
temperature = 10
if weather == “rainy”:
if temperature < 15:
print("Wear a raincoat")
else:
print(’"Take an umbrella")
print("Enjoy your day!") 49