Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

UNIVERSITY OF ABUJA

DEPARTMENT OF COMPUTER SCIENCE


FACULTY OF SCIENCE

CSC 102: INTRODUCTION TO PROBLEM


SOLVING

This lecture material is prepared to introduce and acquaint students with the basic knowledge of
problem solving alongside the tools. In addition, the fundamentals of python programming language
are also highlighted. Importantly, the materials are gathered from Books, Journals and Web
resources.
Lecture 1
Problem Solving Methods
Objectives:
After going through this topic, students would be able to:
➢ Understand meaning of problem
➢ Understand the concept of Problem-Solving Method
➢ Analyse the process of Problem-Solving Method

Overview
Problem-solving (PS) skills are needed in all areas of life, including classroom problem
solving activities. The capacity to decisively analyse a problem, and set up an effective
solution is one of the most valuable skills one can acquire in life, in school, work or in social
circle. Training in this regard promotes cognitive, social development, and can prepare
students with the skills needed to address and solve problems all the way through the rest of
their lives. In reality, whatever activity human being or machine do to achieve a specified
objective comes under problem solving.

1. Problem - Meaning
A problem is a task. Generally, problem is a kind of barrier to achieve something and
problem solving is a process to get that barrier removed by performing some sequence of
activities. Thus, PS is an act of defining a problem; determining the cause of the problem;
identifying, prioritizing and selecting alternatives for a solution; and implementing the
solution.
Learning in a problem-solving method is by working on problems. Students learn new
knowledge by solving problems. This is done through observation, understanding, analysing,
interpreting to find solutions, and performing applications that would give insight to a holistic
understanding of the concepts. Overall, PS is a process - ability to work from known and
discover unknown. Examples of PS:
Example 1: A simple example on input/process/output. Calculate the average grade for all
students in a class.
Input: get all the grades … perhaps by typing them in via the keyboard or by reading them
from a USB flash drive or hard disk.
Process: add them all up and compute the average grade.
Output: output the answer to either the monitor, to the printer, to the USB flash drive or hard
disk … or a combination of any of these devices. To solve the problem, understand the
problem. Thus, these questions???????
▪ What input data/information is available?
▪ What does it represent?
▪ What format is it in?
▪ Is anything missing?
▪ Do I have everything that I need?
▪ What output information am I trying to produce?
▪ What do I want the result to look like … text, a picture, a graph … ?
▪ What am I going to have to compute?

In the example,
➢ the input is a bunch of grades
➢ we need to understand the format of the grades
➢ each grade might be a number from 0 to 100
➢ it may be a letter grade from A+ to F
➢ If it is a number, the grade might be a whole integer like 73 or it may be a real number
like 73.42
➢ need to consider missing grades, if we do not have the grade for every student (e.g.,
some were away during the test) ????
➢ understand what the output should be (output a whole or real number or a letter grade
??????)
➢ display results using charts

The need to understand the processing part of the problem. Break the problem into smaller
problems that require some kind of simple mathematical computations in order to process the
data since we are going to compute the average. So, what is the model (or formula) for
computing the average of a bunch of numbers????? If there is no such “formula”, then, need
to develop one. Sometimes, we can look up certain formulas in a book or online if we get
stuck.
To come up with a model, we need to fully understand the information available to us.
Assuming that the input data is a bunch of integers or real numbers x1,x2,…,xn representing
a grade percentage, we can use the following computational model:
Average1 = (x1 + x2 + x3 + … + xn) / n
Assuming the input number is from 0 to 100.
Conversely, the approach will not work if the input data is a set of letter grades like B-, C,
A+, F, D-, etc.. because we cannot perform addition and division on the letters. Then,
thinking is required.
Assuming, we may decide to assign an integer number to the incoming letters
as follows:
A+ = 12 B+ = 9 C+ = 6 D+ = 3 F = 0
A = 11 B=8 C=5 D=2
A- = 10 B- = 7 C- = 4 D- = 1
If we assume that these newly assigned grade numbers are y1,y2,…,yn, then we can use the
following computational model:
Average2 = (y1 + y2 + y3 + … + yn) / n
where the result will be a number from 0 to 12. The next is formulating an algorithm.

Example 2: On school resumption day, a student is ready to go to school but yet he/she has
not picked up those books and copies which are required as per timetable. As a result, picking
up books and copies according to timetable is a kind of problem solving.
Example 3: Some students in a class plan to host an event and decide to share the expenses
among them. So, making up plans including budgets, noting all activities, risks, alternatives,
etc. is also a kind of problem solving.
The problems that we want to solve can come from any real-world problem or perhaps even
from the abstract world. We need to have a standard systematic approach to solving
problems. The three basic purposes include:
1. Seeking information
2. Generating new knowledge
3. Making decisions

1.1 Objectives of Problem-Solving


• Willingness to try problems and improve their perseverance when solving problems
• Improve the abilities to solve problems
• Recognise problem-solving strategies
• Understand the value of approaching problems in a systematic manner
• Understand that many problems can be solved in more than one way
• Improve the abilities to select appropriate solution strategies
• Improve the abilities to implement solution strategies accurately
• Improve the abilities to get more correct answers to problems
• The appreciation of the existence of a problem and a desire to solve it
• The accumulation of the facts and data which are pertinent to the problem
• Logical interpretation of the data supported by adequate valid experience

1.2 Problem Solving Method Steps


1. Understand the problem. It is basic to comprehend the nature of a problem
and its related goals. Encourage students to frame a problem in their own
words.
2. Describe any barriers. There is need to understand barriers or constraints that
may be preventing from achieving their goal. What is creating the problem?
Verbalize these impediments - always an important step.
3. Identify various solutions. After the nature and parameters of a problem are
understood, then, choose one or more suitable strategies to aid resolve the
problem. Here are some problem-solving possibilities:
• Create visual images. Many problem-solvers find it useful to create
“mind pictures” of a problem and its potential solutions prior to working
on the problem. Mental imaging allows the problem-solvers to map out
many dimensions of a problem and “see” it clearly.
• Guesstimate. Engage in some trial-and-error approaches to problem-
solving. It should be understood, however, that this is not a singular
approach to problem-solving but rather an attempt to gather some
preliminary data.
• Create a table. A table is an orderly arrangement of data. Creating tables
of information, help to group and organize most data relative to a problem.
• Look for a pattern. Looking for patterns is an important problem-solving
strategy because many problems are similar and fall into predictable
patterns. A pattern, by definition, is a regular, systematic repetition and
may be numerical, visual, or behavioural.
• Create a systematic list. Recording information in list form is a process
used quite frequently to map out a plan of attack for defining and solving
problems. Encourage recording ideas in lists to determine regularities,
patterns, or similarities between problem elements.
4 Try out a solution. When working through a strategy or combination of
strategies, it will be important to …
• Keep accurate and up-to-date records of thoughts, proceedings, and
procedures. Recording the data collected, the predictions made, and the
strategies used is an important part of the problem-solving process.
• Try to work through a selected strategy or combination of strategies
until it becomes evident that it's not working, it needs to be modified,
or it is yielding inappropriate data. As students become more proficient
problem solvers, they should feel comfortable rejecting potential strategies
at any time during their quest for solutions.
• Monitor with great care the steps undertaken as part of a solution.
Although it might be a natural tendency to “rush” through a strategy to
arrive at a quick answer, it is vital observe assess and monitor progress.
• Feel comfortable putting a problem aside for a period of time and
tackling it at a later time. For example, scientists rarely come up with a
solution the first time they approach a problem. Problem solvers should
also feel comfortable letting a problem rest for a while and returning to it
later.
5 Evaluate the results. It is important to have multiple opportunities to assess
problem-solving skills and the solutions generated from using those skills. The
process of self-assessment is not easy, however. It involves risk-taking, self-
assurance, and a certain level of independence. But it can be effectively promoted
by asking questions such as “How do you feel about your progress so far?” “Are
you satisfied with the results you obtained?” and “Why do you believe this is an
appropriate response to the problem?”
1.3 Advantages of Problem-Solving Method
• Development of Long-Term Knowledge Retention – the ability to retain
and recall information as a result of open discussion between peers reinforces
understanding of subject matter.
• Use of Diverse Instruction Types - Grouping “students” together allows
them to work together and enjoy team-based learning. Content as video, news
article and more could also be provided.
• Continuous Engagement – It is not hard to see the potential for engagement,
as students collaborate to solve real-world problems that directly affect or
heavily interest them.
• Development of Transferable Skills – It allows learning to become more
profound and durable, helping students apply skills they develop to other real-
world scenarios.
• Improvement of Teamwork and Interpersonal Skills – promotes
interaction and communication, leading to building skills related to teamwork
and collaboration.
Lecture 2

Role of Algorithm in Problem Solving

Objectives
After completing this chapter, students will be able to:
• Know role of algorithm in PS
• Understand what is algorithm
• Understand concept and properties of algorithm
• Know common elements of algorithm
• Understand types of algorithms
• Implement/express algorithm

2. Introduction
Students have a challenge! They need to thank the school management for providing well
equipped computer lab including public address system for them. How do they appreciate
these? They could send thank you note via mail. They could call the Head of Department
(HoD) on phone. They could send email message. They could send representatives to HoD
office. In fact, there are many ways to solve this problem; however, that is not the point.
What is important is that they must decide how to solve the problem and as well, use
appropriate tool to implement their plan.
Assuming representatives are sent to HoD office to deliver them thank you. So, the
representatives are the tool but need to take instruction from the whole students. They have
their mandate on what to say, the time to go, and the message to be delivered. A computer
program is similar to the instruction given to the representatives. The student story is a useful
view concerning computers and computer programs. Every problem solution starts with a
plan. That plan is called an algorithm.

2.1 Role of Algorithm in Problem Solving


One common problem in science has been the overload that occurs when the demand on
working memory exceeds its capacity. Solution to this overload is to help students build
strategies that decrease a task's demand on working memory. These strategies have been
described as the tricks for simplifying problems. Problem solvers go through certain steps
while working a problem. These may be more or less as follows;
✓ begin by reading the problem
✓ perhaps more than once
✓ then write down hopefully, the key information
✓ reread the question or a part of the question
✓ draw a picture to help represent the question
✓ then tried something
✓ tried something else
✓ looked at where this leads
These strategies are algorithms that automate individual steps in solving problem. Thus,
gradually exploring or playing with the question individuals got closer and closer to the
answer.

2.2 Algorithm
Algorithm is the set of step-by-step measures or rules followed to complete a given task or
solve a particular problem. It is “a process that performs some sequence of operations in
order to solve a given problem”. The set of rules must be unambiguous and have a clear
stopping point. Note that there might be other ways to solve a problem; as a result, there may
be more than one algorithm for a problem.
Algorithms are used for calculation, data processing, and many other fields. They are
essential because, algorithms provide the organized procedures that computers require. A
good algorithm is similar to using the exact tool in a workshop. Jobs are done effortlessly.
Using the erroneous algorithm or one that is not plainly defined is like trying to cut a piece of
plywood with a pair of scissors: though it may get done, but how effective could it be in
completing it. So, when solving a problem, the key to arriving at the best solution is often
choosing the right approach.

Example of Algorithm
Problem to solve: Write an algorithm to read two numbers and find their sum.
Inputs to the algorithm (accept two inputs):
• First num1
• Second num2
Expected output:
• Sum of the two numbers
Algorithm:
• Step1: Start
• Step2: input the first num1.
• Step3: input the second num2.
• Step4: Sum = num1+num2
• Step5: Print Sum
• Step6: End

2.3 Concepts and Properties of an Algorithm


An Algorithm must possess the following properties:

• Finiteness: An algorithm must always terminate after a finite number of steps. It


means after every step one reach closer to solution of the problem and after a finite
number of steps algorithm reaches to an end point.
• Definiteness: Each step of must be precisely defined. Actions to be carried out must
to be unambiguously specified for every activity.
• Input: An algorithm should have some inputs. The values are given to the algorithm
before it begins.
• Output: An algorithm has one or more outputs after completing a specified task
based on the inputs.
• Effectiveness: Algorithm operations should be basic and done exactly in a finite
amount of time by a person with pen/paper.

2.4 Characteristics of Algorithm


• Getting specified output is essential after algorithm is executed.
• An algorithm is a finite set of instructions.
• Activities in an algorithm must be clearly defined in other words for it to be
unambiguous.

2.5 Common Elements of Algorithms


• Acquire data (input): Some means of reading values from an external source; most
algorithms require data values to define the specific problem.
• Computation: Performing arithmetic computations, comparisons, testing logical
conditions, etc.
• Selection: Choosing among two or more possible courses of action, based upon initial
data, user input and/or computed results.
• Iteration: Repeatedly executing a collection of instructions, for a fixed number of
times or until some logical condition holds
• Report results (output): Reporting computed results to the user, or requesting
additional data from the user.

2.6 Types of Algorithms


Algorithms are classified according to what they are being used to achieve. The basic types of
computer science algorithms include:
• Divide and conquer algorithms – divide the problem into smaller sub problems of the
same type; solve those smaller problems, and combine those solutions to solve the
original problem.
• Brute force algorithms – try all possible solutions until a satisfactory solution is
found.
• Randomized algorithms – use a random number at least once during the computation
to find a solution to the problem.
• Greedy algorithms – find an optimal solution at the local level with the intent of
finding an optimal solution for the whole problem.
• Recursive algorithms – solve the lowest and simplest version of a problem then, solve
increasingly larger versions of the problem until the solution to the original problem is
found.
• Backtracking algorithms – divide the problem into sub problems, each which can be
attempted to be solved; however, if the desired solution is not reached, move
backwards in the problem until a path is found that moves it forward.
• Dynamic programming algorithms – break a complex problem into a collection of
simpler sub problems, and then solve each of those sub problems only once, storing
their solution for future use instead of re-computing their solutions.

2.7 Importance of Algorithm


The algorithmic thinking is vital in many different fields. Some of the benefits are:
• Allows students to breakdown problems and conceptualize solution in distinct steps
• Being able to understand and implement an algorithm necessitates students to exercise
planned assessment and reasoning abilities.
• By using an algorithm, decision making becomes a more rational process.
• Makes PS process more efficient and consistent

2.8 Implementing/Expressing Algorithms


Algorithms can be expressed in many notations including:
• Natural languages: tend to verbose and ambiguous and rarely used for complex or
technical algorithms.
• Programming language: intended for expressing algorithm in the form that can be
executed by a computer.
• Flow charts and Pseudo codes: both are structured ways to express algorithms that
avoid many ambiguities common in natural language statements, while remaining
independent of a particular implementation language.

Sometimes it is helpful in the description of an algorithm to supplement small flowcharts


with natural language and/or arithmetic expressions written inside block diagrams to
summarize what the flowcharts are accomplishing.
Lecture 3

Flowchart

Objectives
At the end of this chapter, students will be able to:
• Understand flowchart
• Understand flowchart symbols
• Know general rules of flowcharting
• Comprehend types of flowchart

3. Introduction: What is a Flowchart?


Flowchart is a diagram that depicts the flow of data in sequential order through processing
systems. In other words, it makes operations and the sequence of these operations in a system
known. Flow charts are used in different fields to document study, plans, improve and
communicate difficult processes in clear, self-explanatory diagrams. It could be seen as an
outline of a design for solving a problem.
It uses rectangles, ovals, diamonds and potentially other shapes to define the type of step,
along with connecting arrows to define flow and sequence. They can range from simple,
hand-drawn charts to comprehensive computer-drawn diagrams depicting multiple steps and
routes. If we consider all the various forms of flowcharts, they are one of the most common
diagrams on the planet, used by both technical and non-technical people in numerous fields.
Flowcharts are usually drawn at the initial stage of formulating computer solutions. They play
a significant role in the programming of a problem and aid in comprehending the logic of
complex and extensive problems. Once flowchart is drawn, it becomes easy to write
programs.
Example, consider finding the sum, average and product of 3 numbers given by the user.
Algorithm for the given problem is as follows:
Read X, Y, Z
Compute Sum (S) as X + Y + Z
Compute Average (A) as S / 3
Compute Product (P) as X x Y x Z
Display the Sum, Average and Product.

Flowchart for the above problem

3.1 Flowchart Symbols


Flowcharts are generally drawn by means of some standard symbols; nevertheless, some
special symbols can also be developed when needed. Below are some standard symbols that
are frequently used in many computer programs.
3.2 General Rules for flowcharting
The basic guidelines for drawing a flowchart with the above symbols include:
• In drawing a proper flowchart, all necessary requirements should be listed out in
logical order.
• The flowchart should be neat, clear and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
• All boxes of the flowchart are connected with Arrows. (Not lines)
• Flowchart symbols have an entry point on the top of the symbol with no other entry
points. The exit point for all flowchart symbols is on the bottom except for the
Decision symbol.
• For Decision symbol, only one flow line can enter it but with two exit points; these
can be on the sides or the bottom and one side.
• Generally a flowchart will flow from left to right or top to bottom. However, an
upward flow can be shown as long as it does not exceed 3 symbols.
• Connectors are used to connect breaks in the flowchart. Examples are:
o From one page to another page.
o From the bottom of the page to the top of the same page.
o An upward flow of more than 3 symbols
• Subroutines and Interrupt programs have their own and independent flowcharts.
• All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
• All flowcharts end with a terminal or a contentious loop.

Flowcharting uses symbols that have been in use for a number of years to represent the type
of operations and/or processes being performed. The standardised format provides a common
method for people to visualise problems together in the same manner. The use of
standardised symbols makes the flow charts easier to interpret; however, standardizing
symbols is not as important as the sequence of activities that make up the process.

Examples of Flowcharts
To comprehend flowchart techniques, let’s consider these examples.
The figure shows basic flowchart process. Recall what circle shape stands for “connector”.
Here, it connects and extends processes from start to end.
Example1: Consider finding the largest number between A and B
Algorithm for the above problem is as follows:
Read A, B
If A is less than B
BIG=B
SMALL = A
Else
BIG=A
SMALL = B
Display BIG, SMALL
Flowchart for the above algorithm will look like:
Example 2: Find the area of a circle of radius r.
3.3 Types of Flowcharts:
High-Level Flowchart:
A high-level (also known as first-level or top-down) flowchart illustrates the major steps in a
process. It can also include the intermediate outputs of each step (the product or service
produced), and the sub-steps involved.
This type of flowchart presents fundamental picture of the process and identifies the changes
taking place within the process. It is very handy for identifying appropriate team members
(those who are involved in the process) and for developing indicators for checking the
process because of its focus on intermediate outputs.
Most processes can be effectively presented in four or five boxes that symbolize the major
steps or activities of the process

Detailed Flowchart:
It provides a detailed picture of a process by mapping all of the steps and activities that occur
in the process. This type of flowchart indicates the steps or activities of a process and
includes such things as decision points, waiting periods, tasks that frequently must be redone
(rework), and feedback loops. This type of flowchart is useful for examining areas of the
process in detail and for looking for problems or areas of inefficiency.
Given below is the Detailed Flowchart of an Order Filling Process which shows the sub-steps
involved in the process and also reveals the delays that occur when the materials required are
not available in the inventory.
Detailed flowchart.

3.5 Software
Any drawing program can be used to create flowchart diagrams. Some tools offer special
support for flowchart drawing. Currently, many software packages exist that can create
flowcharts automatically, either directly from source code, or from a flowchart description
language. On-line Web-based versions of such programs are available.

3.6 Advantages of Using Flowcharts


Flow chart is used for representing algorithm in symbolic form. These pictorial
representations of a solution/system have many advantages. These include:
• Communication: A Flowchart can be used as a means of communicating the logic of
a system and steps involve in the solution in a clearer manner.
• Effective analysis: A flowchart of a problem can be used for effective analysis of the
problem.
• Documentation of Program/System: Program flowcharts are a vital part of good
program documentation. Program document is used for various purposes like
knowing the components in the program, complexity of the program etc.
• Efficient Program Maintenance: A developed and operational program is easier to
maintain with the help of a flowchart.
• Coding of the Program: It is a good practice to draw flowcharts indicating solutions
for problems. Any design of solution of a problem is finally converted into computer
program with ease.
• Proper Debugging: The flowchart helps in debugging process.
Lecture 4
Pseudocodes
Objectives
Students should at the end of the chapter understand the following:
• What is pseudo code and why is it useful for writing computer programs?
• Solving programming problems with pseudocodes

4. What is Pseudocode?
Literally, pseudo code means “fake code”. It is an artificial and informal approach to writing
sequence of actions and instructions (algorithms) in the form that humans can understand
with ease. In other word, it is a means of describing computer algorithms using a combination
of natural language and programming language. This aids programmers concentrate on the
organization and sequence of a computer algorithm without the need for actually following
the exact coding syntax.

In pseudocode, you don't have to think about semi-colons, curly braces, and the syntax for
arrow functions, how to define promises, DOM methods and other core language principles.
You just have to be able to explain what you are thinking and doing. You make the rules. It
does not matter what language you use to write your pseudocode. All that matters is
comprehension.

4.1 Benefits of Writing Pseudocode


• Using familiar language devoid of core programming syntax and coding patterns
• No official rules to obey
• Acts as a bridge between human brain and computer code executor. Allows plans for
instructions which follow logical pattern without including technical details
• Great way to get started with software programming as a beginner
• It significantly aid problem solving as it involves pragmatic approach
• Makes one take full control and can explain each line of codes
4.2 Solving Programming Problems with Pseudocode
There are no set of rules for pseudocodes exact execution though it is frequently used.
However, below are steps to solving programming with pseudocode.

• Understand what the function does


It is important to understand what a function does. That is, (optionally) accept data as
input compute the data and produce an output. The body of the function is what
actually solves the problem and it does so line by line.
• Make sure you understand the question
Next, read and understand the question properly. This is arguably the most important
step in the process. Adequate problem comprehension helps to figure out all possible
steps towards solutions.
• Break the problem down.
Break down the problem into smaller parts and sub-problems. With each smaller
problem you solve, you'll get closer to solving the main problem.

Once the problem is broken down to the work package, it helps to represent these problem
solving steps in the clearest and most easily understandable way. It is an intermittent step
towards developing the real code. So, programming is the expression of logic. A program is a
set of instructions that defines how software behaves. Thus, coding is how it is implemented
in the computer system.

Example: Illustrating flowchart and pseudocode.


For a given value, Limit, what is the smallest positive integer Number for which the sum
Sum = 1 + 2 + ... + Number is greater than Limit. What is the value for this Sum?

Flowchart:
Pseudocode:

Input: An integer Limit


Ouput: Two integers: Number and Sum

Enter Limit
Set Number = 0.
Set Sum = 0.
Repeat the following:
a. If Sum > Limit, terminate the repetition, otherwise.
b. Increment Number by one.
c. Add Number to Sum and set equal to Sum.
Print Number and Sum.
Lecture 5: Programming Languages
Objectives
At the end of the lecture, students should be able to:
• Understand computer program
• Know programming language and its types
• Understand computer programming

5.1 Computer Program:


A program is a set of instructions following the rules of the chosen language. Without
programs, computers are useless. A program is like a recipe, it contains a list of ingredients
(called variables) and a list of directions (called statements) that tell the computer what to do
with the variables.

5.2 Programming Language:


A vocabulary and set of grammatical rules (syntax) for instructing a computer to perform
specific tasks. Programming languages can be used to create computer programs.

5.2.1 Types of Programming Language


There are three types of programming language:

I. Machine language (Low-level language): This is a binary code of 0’s and 1’s which
the language understand by the computer. It is a collection of binary digits or bits that
the computer reads and interprets. Machine languages are the only languages
understood by computers, while easily understood by computers, machine languages
are almost impossible for humans to use because they consist entirely of numbers.
II. Assembly language (Low-level language): This work between the machine language
and high-level language. It uses mnemonics codes, Low-level languages are closer to
the language used by a computer. A program written in assembly language consists of
a series of instructions mnemonics that correspond to a stream of executable
instructions, when translated by an assembler that can be loaded into memory and
executed. Assembly languages use keywords and symbols, much like English, to
form a programming language but at the same time introduce a new problem. The
problem is that the computer doesn't understand the assembly code, so we need a way
to convert it to machine code, which the computer does understand. Assembly
language programs are translated into machine language by a program called an
assembler.
III. High-level language: High-level languages are closer to human languages. High-level
languages allow us to write computer code using instructions resembling everyday
spoken language (for example: print, if, while) which are then translated into machine
language to be executed. The term programming language usually refers to high-level
languages, which is the language man mostly understand.

5.2.2 Categories of High-level Programming Language


• Imperative
• Procedural and
• Object Oriented

Examples of High-level Language:


• FORTRAN
• ADA
• C
• C++
• JAVA
• BASIC
• COBOL
• PASCAL
• PHYTON

A program written in any programming language need to be converted into machine language
so that the computer can understand it. There are two ways to do this:

I. Compile the program: Compile transform a program written in a high-level


programming language from source code into object code. This is done by using a
tool called compiler. A compiler reads the whole source code and translates it into a
complete machine code program to perform the required tasks which is output.
II. Interpret the program: Interpreter is a program (software) that executes instructions
written in a high-level language. An interpreter reads the source code one instruction
or line at a time, converts this line into machine code and executes it.
5.2.3 Comparing Programming Language Types

Machine Language Assembly High-level


Language Languages
Time to execute Since it is the basic A program called A program called a
language of the an ‘assembler’ is compiler or
computer, it does required to convert interpreter is
not require any the program into required to convert
translation, and machine language. the program into
hence ensures Thus, it takes machine language.
better machine longer to execute Thus, it takes more
efficiency. This than a machine time for a computer
means the language program. to execute.
programs run
faster.
Time to develop Needs a lot of skill, Simpler to use than Easiest to use.
as instructions are machine language, Takes less time to
very lengthy and though instruction develop programs
complex. Thus, it codes must be and, hence, ensures
takes more time to memorized. It takes better program
program. less time to develop efficiency
programs as
compared to
machine language.

5.3 Computer Programming


Computer programming is the process of writing, testing, debugging/troubleshooting, and
maintaining the source code of computer programs. This source code is written in a
programming language like C++, JAVA, Python etc.

Choosing a Programming Language


Before you decide on what language to use, you should consider the following:
• Your server platform
• The server software you run
• Your budget
• Previous experience in programming
• The database you have chosen for your backend
Lecture 6
Object-oriented Programming (OOP)

Objectives:
After going through this topic, students would be able to:
➢ Understand Object-oriented programming
➢ Know what is an object, message, and method
➢ Understand Object-oriented problem-solving approach

6.1 Object-oriented Programming (OOP)


OOP is an approach to problem solving that involves using objects in computations. Thus,
everything in OOP is grouped as objects. An object is a component of a program that knows
how to perform certain actions and how to interact with other elements of the program. It can
represent a person, a bank account or any item that a program can handle. Thus, objects are
the basic units of object-oriented programming. The set of actions that the object performs
defines its behaviour.

When a program is executed, the objects interact by sending messages to one another. For
example, consider “student status” as an object can tell average grade point, year in school, or list of
registered courses, etc. An object asks another object to perform an action by sending it a message.
The requesting (sending) object is referred to as sender and the receiving object is referred to
as receiver. Control is given to the receiving object until it completes the command; control then
returns to the sending object. For example, a School object asks the Student object for its name by
sending it a message asking for its name. The receiving Student object returns the name back to the
sending object.

More example, if ‘customer’ and ‘account’ are two objects in a program, then the customer
object may send message to account object requesting for a bank balance. Each object
contains data and code to manipulate data. Objects can interact without having to know
details of each other’s data or code. It is sufficient to know the type of message accepted and
the type of response returned by the objects.

A message can also contain information the sending objects needs to pass to the receiving
object, called the argument in the message. A receiving object always returns a value back to
the sending object. This returned value may or may not be useful to the sending object. For
example, the School object now wants to change the student's name. It does this by sending
the Student object a message to set its name to a new name. The new address is passed as an
argument in the message. In this case, the School object does not care about the return value
from the message.

The message can trigger other messages to be delivered to it or to other objects in order to
complete its task. This is known as sequential operation. A message has code that associated
with it. When an object receives a message, code is executed. As mentioned, messages
determine an object's behaviour and the code determines how the object carries out each
message. The code that is associated with each message is called a method. The message
name is also called the method name due to its close association with the method. When an
object receives a message, it determines what method is being requested and passes control to
the method. An object has as many methods as it takes to perform its designed actions.
Methods that operate on specific objects are instance methods and messages that invoke
instance methods are called instance message. Methods that operate on specific classes
are class methods

6.2 Object-oriented Problem-Solving Approach


Object-oriented problem-solving approach is similar to how human solves daily problems. It
involves identifying the objects and how to use these objects in the correct sequence to solve
the problem. In other words, object-oriented problem solving can consist of designing objects
whose characteristics solve a specific problem. A message to an object causes it to perform
its operations and solve its part of the problem. The approach can be divided into the
following steps:

• Identify the problem


• Identify the objects needed for the solution
• Identify the message to be sent to the objects
• Create a sequence of messages to the objects that solve the problem

Let’s use the simple example to illustrate these steps.

➢ Problem Identification: Compute the sum of two numbers and print out the result.
➢ Objects Identification: Identify objects needed to solve the problem.
a. First number (object)
b. Second number (object)
c. Result of the addition (Sum)(object)
➢ Message Identification: Message needed to send to objects. This is the message sent
to the receiver object. The result of this message is the value (a numeric object) of the
total sum of the receiver object. It also includes a message that displays the value of
the receiver object, in this case; print.
➢ Object-message sequences: This sequence to solve the problem is;

(First_num + Second_num) print

The message + with parameter Second_num (an object), is sent to the object
First_num. The result is an object (First_num + Second_num), then, the
message print is sent. The parentheses are included to avoid any ambiguity as
to which message should be activated first.

Note: The sequence of evaluation is from left to right unless is specified by parentheses ( ).
For example:

2 + 3 * 4 = 20
2 +(3 * 4) = 14
Lecture 7
Basic Introduction to Python Programming Language
Learning Objectives
The objectives of this course are to get you started with the basic introduction to Python as
the programming language and give you a taste of how to start working with data in Python.
In this course you will learn about:
• What Python is and why is it useful
• The application of Python
• How to define variables
• Data types in python
• Python collection (data structures)

Introduction
This topic teaches the basics of Python and begins by exploring what and why python along
with some of the different data types such as integers, real numbers, and strings. Continue
with brief introduction to different python data structures.

7.1 What is Python?


Python is a popular, high-level programming language. It is used for a wide variety of text
processing, system administration and internet-related tasks. Python is an object-oriented
language, and is available on a wide variety of platforms. There’s even a python interpreter
written entirely in Java, further enhancing python’s position as an excellent solution for
internet-based problems. It was created by Guido van Rossum, and released in 1991.

7.2 Why Python?


Python is simpler to use, available on Windows, Mac OS X, and Unix operating systems, and
will help get the job done more quickly. It is a real programming language, offering much
more structure and support for large programs than shell scripts or batch files can offer. On
the other hand, Python also offers much more error checking than C, and, being a very-high-
level language, it has high-level data types built in, such as flexible arrays and dictionaries.
Python allows split of program into modules that can be reused in other Python programs. It
comes with a large collection of standard modules that can be used as the basis of your
programs — or as examples to start learning to program in Python. Some of these modules
provide things like file I/O, system calls, sockets, and even interfaces to graphical user
interface toolkits.
Python is an interpreted language, which can save you considerable time during program
development because no compilation and linking is necessary. The interpreter can be used
interactively, which makes it easy to experiment with features of the language, to write
throw-away programs, or to test functions during bottom-up program development. These are
highlighted as follow:
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc)
• Python has a simple syntax similar to the English language
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick
• Python can be treated in a procedural way, an object-oriented way or a functional way
• Python can be written in text editors and various integrated development environment
(IDE) (Thonny, Pycharm, Netbeans Eclipse, etc) which are particularly useful when
managing larger collections of Python files.

7.3 Python Syntax compared to other programming languages


• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.
Python provides certain level of freedom when composing a program, but there are some
rules which must always be obeyed. One of these rules, is that python uses indentation (ie,
the amount of white space before the statement itself) to indicate the presence of loops,
instead of using delimiters like curly braces ({}) or keywords (like “begin” and “end”) as in
many other languages. The amount of indentation that can be used is not important, but it
must be consistent within a given depth of a loop, and statements which are not indented
must begin in the first column. Most IDEs automatically provide consistent indentation
which makes it easier to maintain programs.
7.4 What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

7.5 Installing Python


Many PCs and Macs will have python already installed. To check if you have python
installed on a Windows PC, search in the start bar for Python or run the following on the
Command Line (cmd.exe):
C:\Users\Your Name>python --version
To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:
python --version
If python were not installed on the computer, then it can be downloaded for free from the
following website: https://www.python.org/

7.6 IDLE
IDE stands for integrated development environment (IDE). It is a software tool that a
programmer uses to write and test the program and software. Thus, IDE is a software
environment which usually consists of a software development package containing code
editor and build automation. Other features include syntax highlighting, auto completion, and
smart indent. It also has a debugger with stepping and breakpoints features. This makes
debugging easier. The integrated development and learning environment (IDLE) is the IDE
for python. It is a program that allows users to type programs and run them. There are other
IDEs for Python (PyCharm, Visual studio code, Eclipse, etc.).

7.7 Python Quickstart


The rest of the document introduces various features of the Python language through
examples, beginning with simple expressions, statements and data types, functions and
modules, etc.
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
where "helloworld.py" is the name of your python file.
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
helloworld.py
print("Hello, World!")

7.7.1 The Python Command Line


Python can be run as a command line itself.
Type the following on the Windows, Mac or Linux command line:
C:\Users\Your Name>python or py
Then, start writing any python, including our hello world example
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Oct 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!

To exit python command line, type the following to quit the python command line interface:
exit()

7.7.2 Python Syntax


Command Line: Python syntax can be executed by writing directly
>>> print("Hello, World!")
Hello, World!

It can also be done by creating a python file on the server, using the .py file extension, and
running it in the Command Line
C:\Users\Your Name>python myfile.py
7.7.3 Python Indentation
Indentation refers to the spaces at the beginning of a code line. Python uses indentation to
indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example Syntax Error:
if 5 > 2:
print("Five is greater than two!")

7.7.4 Python Variables


In Python, variables are like containers for storing data values. A variable is created the
moment a value is assigned to it.
Example
Variables in Python:
x=5
y = "Hello, World!”
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Elements of variables can be referenced via indexing and slicing.
Example: Indexing and slicing respectively
Word = “Python”
print(word[0])
print(word[3]) indexing
print(word[0:2]) elements from 0 to 2(excluded) slicing.
7.7.5 Casting
There may be times when it is needed to specify a type on to a variable. This can be done
with casting. Python is an object-orientated language, and as such it uses classes to define
data types, including its primitive types. Casting in python is therefore done using constructor
functions:
• int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
Example Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Example Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

7.7.6 Get the Type


You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))

7.7.7 Single or Double Quotes


String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'

7.7.8 Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a

7.7.9 Variable Names


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Example Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

7.7.10 Multi Words Variable Names


Variable names with more than one word can be difficult to read. There are several
techniques that can be used to make them more readable:

Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

7.7.11 Comments
For documentation purposes, Python offers commenting capability.
Comments start with#, and Python will render the rest of the line as a comment:
Example
#This is a comment.
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line
Example

print("Hello, World!") #This is a comment


A comment does not have to be text that explains the code, it can also be used to prevent
Python from executing code
Example
#print("Hello, World!")
print("Cheers, Mate!")
Also, a multiline string can be used. Since Python will ignore string literals that are not
assigned to a variable, a multiline string (triple quotes) in a code is used and place comment
inside it.
Example
"""This is a comment written in more than just one line"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore
it.

7.8 Data Types


In programming, data type is an important concept. Variables can store data of different
types, and different types can do different things. Python has the following data types built-in
by default, in these categories: Table showing data types.
7.8.1 Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x=5
print(type(x))

7.9 Python Numbers


There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))

7.9.1 Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
7.9.2 Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))

7.10 Python Booleans


Booleans represent one of two values: True or False. In programming an expression can be
evaluated as True or False in python and returns the Boolean answer.
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
When a condition is executed in an if statement, Python returns True or False
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

7.11 Python Operators


Operators are used to perform operations on variables and values. Python divides the
operators in the following groups:
• Arithmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations (+, *, -, /, %, **, //).
• Assignment operators: Assignment operators are used to assign values to variables (=,
+=, -=, *=, /=, %=, //=).
• Comparison operators: Comparison operators are used to compare two values (==, !=,
<, >, =<, =>).
• Logical operators: Logical operators are used to combine conditional statements (and,
or).
• Identity operators: Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory location (is, is
not).
• Membership operators: Membership operators are used to test if a sequence is
presented in an object (in, not in).
• Bitwise operators: Bitwise operators are used to compare (binary) numbers (&, |, >>,
<<, ^,).

7.12 Collections (Arrays)


There are four collection data structure types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable, and unindexed. No duplicate
members.
• Dictionary is a collection which is ordered* and changeable. No duplicate members.
*As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
It is important to understand collection type properties before choosing. Choosing the right
type for a particular data set could mean retention of meaning, and, it could mean an increase
in efficiency or security.

7.12.1 List
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types
in Python used to store collections of data; the other 3 are Tuple, Set, and Dictionary all with
different qualities and usage.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values. List items are indexed, the
first item has index [0], the second item has index [1] etc.
When it is said that lists are ordered, it means that the items have a defined order, and that
order will not change. If new items are added to a list, the new items will be placed at the end
of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.
The list is changeable, meaning that it is possible to change, add, and remove items in a list
after it has been created. Since lists are indexed, lists can have items with the same value:
Example Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

List Length
To determine how many items a list has, use the len() function:
Example Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
In many respect, lists are like tuples. One key difference is they are mutable. Lists can
contain strings, floats, integers. It can nest other lists. This is also applicable to data structure
(nesting).

7.12.2 Tuple
Tuples are an ordered sequence. Tuples are expressed as comma separated elements within
parentheses. The elements are immutable which means they cannot be changed.
Ratings = (10, 9, 5, 8, 7, 4, 9, 6)
These are values inside the parentheses. In Python, there are different types: strings, integer,
and float. They can all be contained in a tuple but the type of the variable is tuple. Each
element of a tuple can be accessed via an indexing, slicing. The first element can be accessed
by the name of the tuple followed by a square bracket with the index number, in this case
zero.
7.12.3 Dictionaries
Dictionaries are a type of collection in Python. A dictionary has key/value pair. The key is
analogous to the index. They are like addresses, but they don't have to be integers. They are
usually characters. The values are similar to the element in a list and contain information. To
create a dictionary, we use curly brackets. The keys are the first elements.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are
presented in key: value pairs, and can be referred to by using the key name.
Example: Implementing Algorithm on PS
Example: Problem: Read two numbers and find the sum as discussed earlier.
• Read question
• Understand it
• Analyse
o Need input (accept 2 numbers)
o Process
o Output (result – sum of 2 numbers)
• Evaluate solution

Algorithm
Start
Input First_num
Input Second_num
Sum = First_num + Second_num
Print Sum
End
Implement in Python
# Program to find the sum of two numbers. It accepts input and process to give sum.
First_num = float(input(“Enter first number “))
Second_num = float(input(“Enter second number “))
Sum = First_num + Second_num
print(Sum)
References
An Introduction to Computer Science and Problem Solving. COMP1405/1005.

Bodner, G. M. (1987). The role of algorithms in problem solving. Journal of Chemical Education .

INSTITUTE OF DISTANCE & OPEN LEARNING. Algorithms, Flowcharts & Program.

Quain, M. C. (2012). Intro Problem Solving in Computer Science.

Swarnika, P. Problem Solving Method. Department of Education, Patna University.

https://www.owlnet.rice.edu/~ceng303/manuals/fortran/FOR3_3.html
https://www.freecodecamp.org/news/what-is-pseudocode-in-programming/

https://www.brainkart.com/article/Algorithm,-Pseudocode-and-Flowchart_6945/

http://esug.org/data/Old/ibm/tutorial/OOP.HTML

You might also like