All Ssc2 Slides

You might also like

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

Socio-Computing Department

Faculty of Economics and Political Science


Cairo University

Computer Applications in Modern


Information Societies (2)
Part 1: Introduction to problem solving

Dr Ghada Deghedi

2022-2023
Lecture 1

1
Course Information
Course Material
Lectures Slides, Book, and Lab Notes
Course on Moodle
Computer Applications in Modern Information Societies II

Contacts:
Email: Ghada_a_d@feps.edu.eg
Office Hours: Room 24a

2
Course Grading System and Evaluation

100
50
50
Semester performance
Final
score

30 20
Class work Mid-term

20 10
Assignments and Assignments in the
quizzes in the lecture section
References
Problems in Information Societies

• In information and knowledge societies, new types of


problems emerge. Understanding how to use computational
thinking to solve real-world problems is a key skill in the
21st century.
• Computational thinking involves formulating problems and
their solutions so that the solutions are presented in a form
that can be effectively carried out by an information
processing agent (a machine, a human or a combination of
both).
• Basically computational thinking produces outcomes that
are precisely formulated; well structured.
5
Course Outline
Introduction to Problem
Solving

Problem Solving tools

Introduction to programing

Introduction to Data analysis using


Python

6
Basic Definitions

Problem Decision
Problem
Solving Making

7
Definition of a Problem:
• A "problem" is a “ ... doubtful or difficult matter requiring
solution; something hard to understand or accomplish or deal
with”.

8
Definition of a Problem:
• A problem exists when there is a perceived gap between what
you expect to happen (a desired state) and what actually
happens (the existing state).

9
Characteristics of Problems
• Problems are problems only when we are
aware of them. Ex: Crisis ---> Solution

• Problems are problems because they have no


easy answers – if they did, they would be
already solved.

• Problems are often confused with solutions

10
Problem types

11
Problem types

12
Problem types

13
Definition of Problem Solving
• Problem solving: is the process of
finding solutions to difficult or
complex issues.
• Problem solving is a set of activities
designed to analyze a situation
systematically and generate,
implement, and evaluate solutions.

14
The Scientific Method vs. The Systems Approach
The Scientific Method The Systems Approach

1.Recognize phenomena in the real 1.Define a problem or opportunity in a


world. systems context.
2.Formulate a hypothesis about the 2.Gather data describing the problem or
causes or effects of the phenomena. opportunity

3.Test the hypothesis through 3.Identify alternative solutions.


experimentation.
4.Evaluate the results of the 4.Evaluate each alternative solution.
experiments.
5.Draw conclusions about the 5.Select the best solution.
hypothesis.
6.Implement the selected solution.
7.Evaluate the success of the
implemented solution. 15
The Difference between Decision
Making and Problem Solving
• Problem solving involves defining a problem and creating solutions for it.
• Decision making is selecting a course of action from among available
alternatives.
• A person must weigh the positives and negatives of each option and
consider all the alternatives
• Problem solving always involves decision making. However, not all
decision making involves solving a problem. For example, a supervisor
may have to make decisions about employees, resources, workload, etc.
without having a problem to solve.

16
Why structured problem solving?
There are several reasons for using a structured,
systematic approach to problem solving:
• Decision making based on data, rather than
guesses.
• Determining root causes of problems, rather
than reacting to superficial symptoms
• Devising permanent solutions, rather than
relying on quick fixes

17
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 1: Introduction to problem solving

Dr Ghada Deghedi

2022-2023
Lecture 2

1
Problem Solving Models

Structured, systematic approach


to solving problems and making
improvements.

2
Six-Steps Problem Solving Model
• Some problem-solving models can be highly
sophisticated and technical.

• Despite its simplicity, this model is comprehensive


enough to address most of problems.

• The steps in this sequence are arranged in a circle to


emphasize the cyclical, continuous nature of the
problem-solving process.

• Each step must be completed before proceeding to the


next step.
SIX-STEP PROBLEM SOLVING MODEL

4
There are several important
characteristics to this model:
• The steps are repeatable
•At any step in the process, your group may decide to
go back and repeat an earlier step.
• The process is continuous
•Simply implementing a solution does not end the
problem-solving process.
•Evaluation of that solution may identify new aspects of
the problem or new problems that need to be addressed
•There is no clear separation between them.-two steps
may frequently overlap.

5
Step One: Define the Problem

6
Step One: Define the Problem
• Problem identification is undoubtedly the most
important⎯ and the most difficult⎯ step in the
process.

• All subsequent steps will be based on how you


define and assess the problem at hand.

7
Step One: Define the Problem

Broad review of the


current situation
(The symptoms and scope of the problem)

Setting a Target

8
Reviewing the current situation
Problem parameters include 4Ws & 1H:
• What is happening (and is not happening)?
• When do the problems occur (& when don’t they
occur)?
• Where are the problems originating or identified?
• Who is involved with the problems (& who is
not)?
• How much the problem is affecting the
organization and its customers?

9
2-Setting the target
The target should be SMART:

S pecific The scope should be clear

M easurable The target should be measurable

A ttainable Aligned to organization direction

R ealistic Given the resource, time & authority available

T imebounded Time for successful achievement is clear

10
Step Two: Determine the Root
Cause(s) of the Problem

11
Step Two: Determine the Root
Cause(s) of the Problem
• Root cause analysis (RCA) is a method of problem solving that
helps people answer the question of why the problem occurred.

12
Root cause analysis Troubleshooting

A reactive process of rapidly


-To solve problems on fixing abnormal conditions by
returning things to familiar
structural basis.
standards, without really
-To ensure problems don’t solving its root causes
return.
-To ensure sustainable
improvements are made.

13
Root cause analysis (RCA)

Steps Tools
Point of
Process
Cause
Mapping
Analysis

Direct Causes The Fishbone


Analysis diagram

Root Causes 5 Why


Analysis Analysis

14
RCA Steps

15
1-The point of cause Analysis

• The point of cause is where the problem is


occurring.
• Use the process map and the collected data to
isolate the problem

16
The Process Map

A process map is a step by step visualization of the process


-It capture what actually happens - not what is supposed to happen!
-It should be kept simple

▪ Understand process inputs and outputs


▪ Understand process relationships, dependencies & bottlenecks
▪ Identify what data is required to understand the process properly
17
2-Direct Causes Analysis

The Fish-bone Diagram


18
2-Direct Causes Analysis

The Fish-bone Diagram


19
3-Root Causes Analysis

20
The 5-why analysis

21
When to stop asking “why”?
It won’t always take 5 ‘whys’ to reach the root
cause
Stop asking why if…
• The causes start becoming more vague (rather
than more specific)
• The causes are outside of the scope of the
project
• The causes become a matter of individual
personality
22
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 1: Introduction to problem solving

Dr Ghada Deghedi

2022-2023
Lecture 3

1
Step Three: Develop Alternative
Solutions

2
Step Three: Develop Alternative
Solutions
Creative problem solving requires you to explore
a full range of viable solutions before reaching a
conclusion.
• Generate as many potential solutions as
possible
• Relate each solution to the causes of the
problem
• Merge similar or related solutions

3
• At this stage, you are still not ready to select the
best solution. You simply want to reduce
redundancy, and eliminate any possibilities that
don’t address the causes you identified earlier.
• A common problem with generating alternatives
is the tendency to evaluate the alternatives as they
are created. This tendency may lead to selecting
the first acceptable, though frequently not
optimal, solution.
4
Techniques for Generating Alternatives

Discussion
Brainstorming Surveys
groups

5
BRAINSTORMING
„The best way how to have a
good idea is to have many
ideas“

using the brain to storm new ideas


individually or in groups

Purpose:
To generate a large number
of ideas in a short period of
time.

6
Brainstorming Guidelines

7
Example
• Situation: The number of customers to a shop
has reduced in recent months; the owner is
looking for new ways to attract new customers
and to increase the frequency of existing
customers
• Problem: How can we get more customers?

8
Surveys
• Surveys economically tap the ideas of a large
group of respondents.
• Surveys present respondents with the problem
and a series of alternative solutions.

9
Discussion groups
• Discussion groups should consist of those who
are directly involved in decision making. In
generating alternatives, the group members
should:
• Be comprehensive.
• Avoid initial judgments (as in brainstorming).
• Focus on the problem, not on the personalities of
the people involved in the decision-making
process. (But be sensitive to the impact of
personalities on the process.)
10
Step Four: Select a Solution

11
Step Four: Select a Solution
• Evaluating alternatives
• Cost-Benefit Analysis (CBA)
• Decision matrix
• Selecting an Alternative
• Satisfactory approach
• Optimal approach

12
Evaluating alternatives

Criteria for Evaluating Alternatives


13
Solutions Effectiveness and Costs

14
Evaluating Solutions Techniques
• Examples of techniques that can help in
evaluating solutions:
– Cost benefit analysis.
– Decision matrix.
Cost-Benefit Analysis (CBA)

Benefits-Costs Ratio= Benefits/Costs

16
Cost-Benefit Analysis Example:

Solution A has the lowest cost while solution C has the highest
Benefits. However , when comparing the costs to benefits we will find
that solution B offers the highest cost-benefit ratio, so from financial
point of view we will select solution B.
17
Decision Matrix
When to Use a Decision Matrix?
• When a list of options must be narrowed to
one choice

• When the decision must be made on the basis


of several criteria (when you have a number of
options available and a number of factors to
consider)

18
A Decision Matrix Example

19
A Decision Matrix Example

20
A Decision Matrix Example

21
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 1: introduction to problem solving

Dr Ghada Deghedi

2022-2023
Lecture 4

1
Selecting an Alternative
› Selecting an alternative is a critical step in the
problem-solving process.
› When selecting an alternative, you will encounter
factors that affect your decision making.
• Political factors.
• Safety factors.
• Financial factors.
• Environmental considerations.
• Ethical factors.

2
Decision Making Approaches

› The satisfactory approach

› The optimal approach.


Satisfactory approach
› Once the decision maker finds an alternative that
meets some minimum standards of acceptability,
that alternative is chosen and implemented, even if
all of the alternatives have not been reviewed.

› Alternatives are evaluated only until one is found


that is “satisfactory,” then it is implemented.
› This means there are likely to be alternatives that
do not get evaluated, since the process is finished
when one that is “good enough” is found.
4
Satisfactory approach

• This process is usually faster, since the


decision maker is trading quality for speed on
purpose.
• The risk is a lower quality decision that is less
effective.
5
Optimal approach
› Critical data is analyzed, alternatives are
identified, and then each alternative is compared
to the criteria.
› Choosing the optimum solution takes more time
than the other approach (the satisfactory
approach).
› In the long run the quality and effectiveness of the
decision is likely to be higher.

6
Optimal approach

• This process is slower than the satisfactory


approach, since the decision maker is trading a
longer amount of time in order to gain quality.
• The risk is a higher quality decision that is too
late
7
Step Five: Implement the Solution

8
Step Five: Implement the Solution

Determine objectives.

Identify needed resources.

Build an action plan.

Implement the plan.


9
Determine objectives
• Objectives are measurable targets that are:
– Used to monitor progress and establish
priorities.

– Based on analysis of the situation.


Identify needed resources
• Resources include:
– People
– Information (data)
– Things.
• What resources do I need?
• Where will I get them?
• How long will it take?
• What can others offer?
• Are there any special requirements?
• Your plan should state:

– Who …

– Will do what (and with whom) …

– By when

– Where

– How
Implement the plan

• Use the action plan to put the decision in place.


Mapping the Plan to Tasks
• The tasks to be managed are the steps that
complete the implementation.
• To assure that necessary deadlines are met.
Problem Solvers Role during
Implementation
• During implementation, problem solvers must be
both
– Proactive; to ensure the problem gets solved.
– Reactive: to make sure they can adjust the
implementation when faced with delays, obstacles, and
surprises.
Step Six: Evaluate the Outcome

16
Step Six: Evaluate the Outcome
• Evaluation is the monitoring that any project
needs to ensure that milestones are met, costs are
contained, and work is completed.
• Feedback mechanisms to detect the need for
midcourse corrections and to ensure that the
problem is solved without creating new problems.
• Collecting data and reporting on what has been
accomplished
Step Six: Evaluate the Outcome
• Monitoring the success and results of a
decision is an ongoing process that is critical to
fine tuning a course of action.

Fine tuning: to adjust precisely so as to bring to the highest


level of performance or effectiveness
18
Assignment (1) – 5 Marks
There are many problem-solving models. We learned one of them in the lecture: The Six-Step
Problem Solving Model. In this assignment, you are requested to:

1. Conduct your own research and choose one different problem-solving model other than the
model we have learned in the lecture. Describe that model and state the differences between it
and the Six-Step problem-solving model.

2. Choose a social problem (economic, social, political, etc.) and use the model you have chosen
and described to define and solve it (you have to use at least 3 tools that we have learned in
the lecture).

› Group size: 1-5 students per group

› Format: a report in Microsoft Word, PDF or PowerPoint summarizing the definition of your problem
and how you applied your selected model to solve it.

› Due date: by 10:00PM, Saturday, 22 October (late delivery will not be accepted).

› Delivery: All assignment should be uploaded on Moodle

› More information will be given in the section


Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 2: Problem Solving Tools

Dr Ghada Deghedi

Lecture 5 2022-2023

1
Introduction
• In problem solving, algorithm development and coding we
tend to view problems at different levels of abstraction

2
Introduction
• In Part 1, we illustrated the working of problem
solving from a general perspective.
• In computing, we focus on the type of problems
categorically known as algorithmic problems,
where their solutions are expressible in the form
of well-defined procedure consisting of a set of
instructions, that takes some value or set of
values, as input, and produces some value or set
of values, as output.
Heuristic solutions: require reasoning built on knowledge and experience, and
a process of trial and error. (not guaranteed to be optimal put satisfactory)
3
Introduction
• A cooker, for instance, follows a procedure commonly known
as a recipe that converts the ingredients (input) into some
culinary dish (output), after a certain number of steps.

Inputs Procedure Output

4
Introduction
• An algorithm, is a form that embeds the complete
logic of the solution. Its formal written version is
called a computer program, or code.
• Thus, algorithmic problem solving actually
comes in two phases:
Derivation of an algorithm that solves the
problem

Conversion of the algorithm into code

5
Introduction
• Computer programming can be divided into
three distinct areas of activity:
• 1. Problem definition and problem solving
• 2. Creating a structured solution (or algorithm)
• 3. Coding (e.g. Java, Python, C++)

6
• Has no intelligence or thinking power.
• The Intelligence Quotient (I.Q) of a computer is zero.
• A computer performs many tasks exactly in the same manner as it is
told to do.
• People are better than computers at developing heuristic solutions.
• Computers are built to deal with algorithmic solutions, which are
often difficult or very time consuming for humans.
• The field of computers that deals with heuristic types of problems is
7
called artificial intelligence.
Introduction
• In order to instruct a computer program
correctly, the user must have clear
understanding of the problem to be solved.
Apart from this he should be able to develop a
method, in the form of series of sequential
steps, to solve it.
• Once the problem is well-defined and a
method of solving it is developed, then
instructing the computer to solve the problem
becomes relatively easier task.
8
Algorithms
• The word algorithm comes from the name of a
mathematician Abu Ja’far Mohammed ibn-i
Musa al Khowarizmi.

9
Algorithms: Real Life Examples
◼ Many Real-Life Examples
 Cooking: Recipe for preparing a dish
 Origami: The Art of Paper Folding
 Directions: How to go to Cairo Airport

 Example: how do you make a cup of tea?

1. Boil kettle
2. Put tea in cup
3. Pour boiling water
into cup

10
Informal definition of an algorithm
Computer Algorithms
A set of sequential steps usually written in Ordinary Language to
solve a given problem is called Algorithm. It is used for
obtaining a required output for any legitimate input in a finite
amount of time.

problem

algorithm

input “computer” output

12
Algorithm Definition
• An algorithm can be defined as “a complete,
unambiguous, finite number of logical steps
for solving a specific problem “

Unambiguous No room for subjective


interpretation

13
Algorithms
• It may be possible to solve to problem in more than
one way, resulting in more than one algorithm.
• The choice of various algorithms depends on the
factors like reliability, accuracy and easy to modify.
• The most important factor in the choice of algorithm
is the time requirement to execute it, after writing
code in High-level language with the help of a
computer. The algorithm which will need the least
time when executed is considered the best.

14
Steps involved in algorithm development
• Step1: Identification of input: For an algorithm, there are
quantities to be supplied called input and these are fed
externally. The input is to be identified first for any specified
problem.
• Step2: Identification of output: From an algorithm, at least
one quantity is produced, called for any specified problem.
• Step3: Identification the processing operations: All the
calculations to be performed in order to lead to output from the
input are to be identified in an orderly manner.

15
Properties of an efficient algorithm

16
Properties of an efficient algorithm
• Finiteness: An algorithm must terminate in a finite number of steps
• Definiteness: Each step of the algorithm must be clear and unambiguous.
• Effectiveness: Each step must be effective, in the sense that it should be
primitive easily convertible into program statement , can be performed
exactly in a finite amount of time.(steps must be doable).
• Input/output: Each algorithm must take zero, one or more quantities as
input data and produce one or more output values.
• Generality: The algorithm must be complete in itself so that it can be used
to solve problems of a specific type for any input data.

17
Three constructs
Example 1
Find the average of three numbers

• Step 1: Read the numbers a, b, c


• Step 2: Compute the sum of a, b and c
• Step 3: Divide the sum by 3
• Step 4: Store the result in variable d
• Step 5: Print the value of d
• Step 6: End
19
Example 2
Write an algorithm to calculate the simple interest using
the formula. Simple interest = P*N* R/100
Where P is principle Amount, N is the number of years and R is the
rate of interest.

• Step 1: Read the three input quantities’ P, N


and R.
• Step 2: Calculate simple interest as Simple
interest = P* N* R/100
• Step 3: Print simple interest.
• Step 4: End

20
Example 3
Write an algorithm to find the area of the
triangle. Let b, c be the sides of the triangle ABC and A
the included angle between the given sides.

• Step 1: Input the given


elements of the triangle
namely sides b, c and angle
between the sides A.
• Step 2: Area = (1/2) *b*C*
sin A
• Step 3: Output the Area
• Step 4: End
21
Example 4
Write an algorithm to calculate the perimeter and
area of rectangle. Given its length and width.
• Step 1: Read length of the rectangle.
• Step 2: Read width of the rectangle.
• Step 3: Calculate perimeter of the rectangle using
the formula perimeter = 2 * (length + width)
• Step 4: Calculate area of the rectangle using the
formula area = length*width.
• Step 5: Print perimeter.
• Step 6: Print area.
• Step 7: End 22
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 2: Problem Solving Tools

Lecture 6

Dr Ghada Deghedi
2022-2023

1
Example 5
Write an algorithm to find the largest of
three numbers X, Y,Z.
• Step 1: Read the numbers X,Y,Z.
• Step 2: if (X > Y)
• Big = X
• else BIG = Y
• Step 3: if (BIG < Z)
• Step 4: Big = Z
• Step 5: Print the largest number i.e. Big
• Step 6: Stop.
2
Finding the largest integer
among five integers
12 8 13 9 11

• Step 1: Set the 12 to the Largest numbers.


• Step 2: 12 is larger than 8 ,there is no need to change
the value of Largest.
• Step 3: 13 is larger than 12 , the algorithm changes the
value of Largest to 13 and moves to the next step.
• Step 4: Nothing is changed in this step, because 13 is
larger than 9.
• Step 5: Again nothing is changed , because 13 is larger
than 11.
• Step 6: print largest

4
Defining actions in FindLargest algorithm
FindLargest refined
Generalization of FindLargest
Three constructs
Loop Design

Initializing a Control Variable


I=1

While (I <= 100 ) Do Testing Loop Condition

Print “Hello Feps” Statement (s) to repeat

I=I+1 Updating the Control Variable

This algorithm prints the message “Hello Feps” 100 times


9
Loop Design

Initializing a Control Variable


Counter = 1

While (Counter <= 10 ) Do Testing Loop Condition

Print Counter Statement (s) to repeat

Counter = Counter + 1 Updating the Control Variable

This algorithm prints the numbers between 1 and 10 to


the screen
10
Example 6
Write an algorithm to find the factorial of a
given number N (N!=1*2*3 …*N)
Step1: Read N
Step2: PROD = 1

Step3: I=2
Step4: While (I <= N) do
Step5: PROD = PROD* I
Step6: I=I+1

Step7: Write “Factorial of ”, N, “ is ”, PROD


Step8: End
11
Tracing: Testing the algorithm
Will the algorithm work to get factorial of 4? (4! = 1*2*3*4)
Step1: Read N N=4
Step2: PROD = 1 PROD = 1
I=2
IF I (2) <= N (4) ? Yes
Step3: I = 2
PROD = 1 * 2 = 2
Step4: While (I <= N) do
I=2+1=3
Step5: PROD = PROD* I IF I (3) <= N (4) ? Yes
Step6: I=I+1 PROD = 2 * 3 = 6
I=3+1=4
Step7: Write “Factorial of ”, N, “ is ”, PROD IF I (4) <= N (4) ? Yes
Step8: End PROD = 6 * 4 = 24
I=4+1=5
IF I (5) <= N (4) ? NO

Factorial of 4 is 24
12
Example 6
Write an algorithm to find the factorial of a
given number N
• Step 1: PROD = 1
• Step 2: I = 0
• Step 3: read N
• Step 4: While I < N do
• I=I+1
• PROD = PROD* I
• Step 5: Write “Factorial of”, N, “is”, PROD
• Step 6: End
13
Example 7
Write an algorithm to find the sum of given data
values until a negative value is entered.
NEW_VALUE: 5, 10, 7, …, -1
Step1: SUM = 0
Step2: Read NEW_VALUE
Step3: While (NEW_VALUE > = 0) Do
Step4: SUM = SUM + NEW_VALUE
Step5: Read NEW_VALUE

Step6: Write “The sum is ” SUM


Step7: End
14
Tracing: Testing the algorithm
Will the algorithm work to get the sum of
these three numbers 5, 10, 7?
Step1: SUM = 0 SUM = 0
NEW_VALUE =5
Step2: Read NEW_VALUE
IS NEW_VALUE (5) >=0 ? YES
Step3: While (NEW_VALUE > = 0) Do SUM= 0 +5 = 5
Step4: SUM = SUM + NEW_VALUE NEW_VALUE = 10
IS NEW_VALUE(10) >=0 ? YES
Step5: Read NEW_VALUE
SUM= 5 + 10 = 15
NEW_VALUE = 7
Step6: Write “The sum is ” SUM IS NEW_VALUE(7) >=0 ? YES
Step7: End SUM= 15 + 7 = 22
NEW_VALUE = -1
IS NEW_VALUE(-1) >=0 ? NO

The sum is 22
15
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University

Computer Applications in Modern


Information Societies (2)
Part 2: Problem Solving Tools

Lecture 7

Dr Ghada Deghedi
2022-2023

1
Flowcharts
• A flowchart visual or graphical representation of an algorithm.
• A flowchart is a diagram made up of boxes,
diamonds and other shapes, connected by arrows.
Each shape represents a step in the process, and the
arrows show the order in which they occur.
• The flowcharts help to analyze the problem and
plan its solution in a systematic and orderly
manner.
• A flowchart when translated into a proper computer
language, results in a complete program.
2
Advantages of Flowcharts
1. The flowchart shows the logic of a problem
displayed in pictorial fashion which felicitates
easier checking of an algorithm.
2. The Flowchart is good means of communication
to other users. It is also a compact means of
recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to
break the problem into parts. These parts can be
connected to make master chart.
4. The flowchart is a permanent record of the
solution which can be consulted at a later time.

3
Differences between Algorithm and Flowchart

Algorithm Flowchart
• A method of representing the step-by- • A diagrammatic representation of an
step logical procedure for solving a algorithm. It is constructed using
problem. different types of boxes and symbols.

• It contains step-by-step English


• The flowchart employs a series of blocks
descriptions, each step representing a
and arrows, each of which represents a
particular operation leading to solution of
particular step in an algorithm.
problem.

• These are particularly useful for small • These are useful for detailed
problems. representations of complicated programs.

• For complex programs, algorithms prove • For complex programs, Flowcharts


to be Inadequate. prove to be adequate.
4
Symbols used in Flowcharts

Symbol Name Function

used to indicate either START/ STOP


Oval
of the program.

Parallelograms are used to represent


input and output operations.
Input and output
Statements like INPUT, READ and
indicators
PRINT are represented in these
Parallelograms.

Rectangle is used to indicate any set of


Process Indicators processing operation such as for
storing arithmetic operations.

5
Symbols used in Flowcharts

The diamond is used for indicating the


step of decision making and therefore
known as decision box. Decision boxes
Decision Makers are used to test the conditions or ask
questions and depending upon the
answers, the appropriate actions are
taken by the computer.

Flow lines indicate the direction being


followed in the flowchart. In a
Flow Lines Flowchart, every line must have an
arrow on it to indicate the direction. The
arrows maybe in any direction.

6
Circles are used to join the different parts
of a flowchart and these circles are called
on-page connectors. The uses of these
connectors give a neat shape to the
On- Page flowcharts. In complicated problems, a
connectors flowchart may run in to several pages.
The parts of the flowchart on different
pages are to be joined with each other.
The parts to be joined are indicated by
the circle.
This connector represents a break in the
path of flowchart which is too large to fit
on a single page. It is similar to on-page
Off-page
connector. The connector symbol marks
connectors
where the algorithm ends on the first
page and where it continues on the
second. 7
General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. 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.

3. The Decision symbol has two exit points; these can be on the sides
or the bottom and one side.

4. Generally a flowchart will flow from top to bottom.

8
General Rules for flowcharting

5. Connectors are used to START A

connect breaks in the


flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top
of the same page. END
A
• An upward flow of more than 3
symbols
6. All flowcharts end with a
terminal. END

9
Flowcharts’ main structures

Sequence Decision Loop

10
Decision )
Binary(structure

• Note: there are two acceptable ways to represent a decision in all


of the structures. Either method is acceptable.

11
Repetition Structure
An essential feature of repetition is that each loop has a
termination condition to stop the repetition.
The termination condition can be checked or tested
1. At the beginning and is known as a pre-test loop or
2. At the end of the loop and is known as a post-test loop.

Pre-test Repetition
Post-test Repetition
flowchart
flowchart

12
Example 1
Draw the Flowchart to find the average
of three numbers

• Step 1: Read the numbers a,


b, c
• Step 2: Compute the sum of
a, b and c
• Step 3: Divide the sum by 3
• Step 4: Store the result in
variable d
• Step 5: Print the value of d
• Step 6: End

13
Example 2
Draw the Flowchart to find out the biggest of
the three unequal positive numbers.
Start
• Step 1: Read the numbers
X,Y,Z.
• Step 2: if (X > Y)
Input a,b,c

Yes No
• Big = X
IS a > b? • else BIG = Y
No No • Step 3: if (BIG < Z)
IS a > c? IS b > c?
• Step 4: Big = Z
Yes Yes
• Step 5: Print the largest
Print a Print c Print b number i.e. Big
• Step 6: Stop.

Stop 14
Example 3
Draw the Flowchart for adding the integers
from 1 to 100 and to print the sum.
Start

Sum = 0
N =1

Yes

IS
N > 100?

Print Sum
No

Sum = Sum + N
Stop
N=N+1

15
Example 4
Draw a flowchart to find the factorial of given
positive integer N.
• Step 1: read N
• Step 2: I = 0
• Step 3: PROD = 1
• Step 4: While I < N do
• I=I+1
• PROD = PROD* I
• Step 5: Write “Factorial
of”, N, “is”, PROD
• Step 6: End
16
Example 5
ABC company plans to give a 6% year end bonus to each of its
employees earning EGP 6,000 or more per month, and a fixed
EGP 250 bonus to the remaining employees. Draw a flowchart for
calculating the bonus for an employee
Start

Input salary

No Yes
IS
salary ≥ 6000

Bonus = 250 Bonus = 0.06 * salary

Print Bonus

Stop
17
Example of Algorithms and Flowcharts
Design an algorithm and the corresponding flowchart
for adding the test scores as given below:
26, 49, 98, 87, 62, 75

a) Algorithm
1. Start 9. Get the Forth testscore
2. Sum = 0
10. Add to sum
3. Get the first testscore
4. Add first testscore to 11. Get the fifth testscore
sum 12. Add to sum
5. Get the second testscore 13. Get the sixth testscore
6. Add to sum
14. Add to sum
7. Get the third testscore
8. Add to sum 15. Output the sum
16. Stop 18
B. Flowchart

19
20
The Pseudo code
• The Pseudo code is neither an algorithm nor a
program. It is an abstract form of a program. It
consists of English like statements which perform the
specific operations. It is defined for an algorithm. It
does not use any graphical representation. In pseudo
code, the program is represented in terms of words
and phrases, but the syntax of program is not strictly
followed
Advantages of pseudo code
• Easy to read.
• Easy to understand.
• Easy to modify.

21
Example of pseudo code
Write a pseudo code to perform the basic arithmetic
operations.

• Read n1, n2
• Sum = n1 + n2
• Diff = n1 – n2
• Mult = n1 * n2
• Quot = n1/n2
• Print sum, diff, mult, quot
• End.
22
Difference between Algorithm, Pseudocode and Program

• Algorithm: Systematic logical approach, which


is a well-defined, step-by-step procedure that
allows a computer to solve a problem.
• Pseudocode : It is a simpler version of a
programming code in plain English which uses
short phrases to write code for a program before
it is implemented in a specific programming
language.
• Program : It is exact code written for
problem following all the rules of the
programming language.
23
Computer Applications in Modern Information Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 8
Reference

Charles R. Severance
Introduction

Two phases are required for a typical programing task

Problem solving phase

Define the problem and produce an ordered sequence of steps that


describe solution of problem (algorithm)

Implementation phase

Implement the program in some programming language

Programming means designing or creating a set of instructions to ask the computer to


carry out certain jobs which normally are very much faster than human beings can
do.
Introduction

 Writing programs (or programming) is a very creative and rewarding activity.

 You can write programs for many reasons, ranging from making your living to
solving a difficult data analysis problem to having fun to helping someone else
solve a problem.

 We are surrounded in our daily lives with computers ranging from laptops to cell
phones.
Introduction

 Programmers add an operating system and a set of applications to the hardware and we end up with a
Personal Digital Assistant (PDA) that is quite helpful and capable of helping us do many different things.

 We can think of these computers as our “personal assistants” who can take care of many things on our
behalf.

 The hardware in our current-day computers is essentially built to continuously ask us the question, “What
would you like me to do next?”
Introduction

Computers are good at things that humans are not

This is why you need to become skilled at talking “computer language”. Once you learn
this new language, you can delegate mundane tasks to your partner (the computer), leaving
more time for you to do the things that you are uniquely suited for.
Example: reading and understanding text from a piece of paper- counting the words and
telling how many times the most used word was used.
Our Objective

 For now, our primary motivation is not to make money or please end users.

 To be more productive in handling the data and information that we will


encounter in our lives.

 When you first start, you will be both the programmer and the end user of
your programs.

 As you gain skill as a programmer and programming feels more creative to


you, your thoughts may turn toward developing programs for others.
Computer hardware architecture
The Central Processing Unit
 The Central Processing Unit (or CPU) is the part of
the computer that is built to be obsessed with “what is
next?”

 If your computer is rated at 3.0 Gigahertz, it means


that the CPU will ask “What next?” three billion times
per second.
The Main Memory
 The Main Memory is used to store information that the
CPU needs in a hurry.

 The main memory is nearly as fast as the CPU.

 But the information stored in the main memory vanishes


when the computer is turned off.
The Secondary Memory
 The Secondary Memory is also used to store
information, but it is much slower than the main
memory.
 The advantage of the secondary memory is that it can
store information even when there is no power to the
computer.
 Examples of secondary memory are disk drives or flash
memory (typically found in USB sticks and portable
music players).
The Input and Output Devices

 The Input and Output Devices are simply our screen,


keyboard, mouse, microphone, speaker, touchpad,
etc.
 They are all of the ways we interact with the
computer.

Networks: These days, most computers also have


a Network Connection to retrieve information over
a network
Programmer’s job
 As a programmer, your job is to use and orchestrate each of these resources to solve
the problem that you need to solve and analyze the data you get from the solution.

 As a programmer you will mostly be “talking” to the CPU and telling it what to do
next.

 Sometimes you will tell the CPU to use the main memory, secondary memory,
network, or the input/output devices.

 You need to be the person who answers the CPU’s “What next?” question.

 It would be very uncomfortable to shrink you down to 5mm tall and insert you into the
computer just so you could issue a command three billion times per second.

 Instead, you must write down your instructions in advance.

 We call these stored instructions a program and the act of writing these instructions
down and getting the instructions to be correct programming.
Understanding programming
 In the end you will be a programmer - perhaps not a professional programmer.

 You will have the skills to look at a data/information analysis problem and develop a
program to solve the problem.
Skills to be a programmer
 First, you need to know the programming language (Python) - you need to know the vocabulary and the
grammar.

 You need to be able to spell the words in this new language properly and know how to construct well-formed
“sentences” in this new language.

 Second, you need to “tell a story”.

 In writing a story, you combine words and sentences to convey an idea to the reader.

 There is a skill and art in constructing the story, and skill in story writing is improved by doing some writing
and getting some feedback.

In programming, our program is the “story” and the problem you are trying to solve is the “idea”.
Skills to be a programmer

Once you learn one programming language such as Python, you will find it much easier to learn a
second programming language such as JavaScript or C++. The new programming language has
very different vocabulary and grammar but the problem-solving skills will be the same across all
programming languages

Start reading and explaining programs,

then we write simple programs,

and then we write increasingly complex


programs over time.
Words and sentences

 Unlike human languages, the Python vocabulary is actually pretty small.

 We call this “vocabulary” the “reserved words”. These are words that have very special
meaning to Python.

 When Python sees these words in a Python program, they have one and only one meaning
to Python.

 You can make up your own words that have meaning to you called variables.

 You will have great latitude in choosing your names for your variables, but you cannot use
any of Python’s reserved words as a name for a variable.
Words and sentences
 The reserved words in the language where humans talk to Python include the following:

Talking to Python is like human-to-dog language. For example, if you


say, “I wish more people would walk to improve their overall health”,
what most dogs likely hear is, “blah blah blah walk blah blah blah blah.”
That is because “walk” is a reserved word in dog language.
Programming Languages
 Programming a computer by hand, i.e., constructing the memory layout byte-by-byte is an
extremely hard, if not impossible, task.
 The byte-by-byte memory layout corresponding to a program is called the machine code.
Interestingly, the first programming had to be done the most painful way.
 You need to be able to program computer using a more sophisticated set of instructions and data
that are more understandable by humans, and you need a tool which will translate this human
comprehensible form of the instructions and data (numbers and characters, at least), into that
cumbersome, ugly looking, incomprehensible sequence of bytes; i.e., machine code.
 Computers cannot write programs on their own as they don’t understand human needs unless we
communicate with the computer through programming languages.
 A programming language is a computer language engineered to communicate instructions to a
machine.
 Programs are created through programming languages to control the behavior and output of a
machine through accurate algorithms, similar to the human communication process.
Types of programming languages
Machine Language
 Machine language, also called machine code, is a low-level computer language that is designed to be directly
understandable by a computer and it is the language into which all programs must be converted before they
can be run.

 It is entirely comprised of binary, 0’s and 1’s. In machine language, all instructions, memory locations,
numbers and characters are represented in 0’s and 1’s.

 The main advantage of machine language is that it can run and execute very fast as the code will be directly
executed by a computer and the programs efficiently utilize memory.

 Some of the disadvantages of machine language are,


Machine language is almost impossible for humans to use because it consists entirely of
numbers.
Machine language programs are hard to maintain and debug.
Machine language has no mathematical functions available.
Memory locations are manipulated directly, requiring the programmer to keep track of
every memory location.
Assembly Language
 Machine language is extremely difficult for humans to read because it consists merely of patterns of bits (i.e., 0’s and 1’s). Thus,
programmers who want to work at the machine language level instead usually use assembly language, which is a human-readable
notation for the machine language.
 Assembly language replaces the instructions represented by patterns of 0’s and 1’s with alphanumeric symbols also called as mnemonics
in order to make it easier to remember and work with them including reducing the chances of making errors. For example, the code to
perform addition and subtraction is,
ADD 3, 5, result
SUB 1, 2, result
 Since the computer cannot understand assembly language, it uses another program called assembler. Assembler is a program that is used
to convert the alphanumeric symbols written in assembly language to machine language and this machine language can be directly
executed on the computer.
 Some of the disadvantages of Assembly language are,

 There are no symbolic names for memory locations.


 It is difficult to read.
 Assembly language is machine-dependent making it difficult for portability.
High-Level Language
 High- level languages are written in a form that is close to our human language, enabling programmers to
just focus on the problem being solved.

 High-level languages are platform independent which means that the programs written in a high-level
language can be executed on different types of machines.

 A program written in the high-level language is called source program or source code.

 For a computer to understand and execute a source program written in high-level language, it must be
translated into machine language. This translation is done using either compiler or interpreter.

 Advantages

 Easier to modify, faster to write code and debug as it uses English like statements.

 Portable code, as it is designed to run on multiple machines.


Interpreter and compiler
 Python is a high-level language intended to be relatively straightforward for humans to read and write and for
computers to read and process.

 Other high-level languages include Java, C++, PHP, Ruby, Basic, Perl, JavaScript, and many more.

 Translators are built to allow programmers to write in high-level languages like Python or JavaScript and
these translators convert the programs to machine language for actual execution by the CPU.

Interpreters
Compilers. Programming
language
translators
Interpreter
 An interpreter reads the source code of the program as written by the programmer, parses
the source code, and interprets the instructions on the fly.

 Python is an interpreter and when we are running Python interactively.

 We can type a line of Python (a sentence) and


Python processes it immediately and is ready for
us to type another line of Python.

Example:
>>> x=6
>>> print (x)
6
>>>
Compiler
 A compiler needs to be handed the entire program in a file, and then it runs a
process to translate the high-level source code into machine language and then
the compiler puts the resulting machine language into a file for later execution.

 If you have a Windows system, often these executable machine language


programs have a suffix of “.exe” or “.dll” which stand for “executable” and
“dynamic link library” respectively.

 If you were to open an executable file in a text editor, it would look completely
crazy and be unreadable.
Python interpreter
 The Python interpreter is written in a high-level language called “C”.

 You can look at the actual source code for the Python interpreter by going to

www.python.org

 Python is a program itself and it is compiled into machine code.

 When you installed Python on your computer, you copied a machine-code


copy of the translated Python program onto your system.
Computer Applications in Modern Information Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 9
What is a program?

❑ The definition of a program at its most basic is a


sequence of statements that have been crafted to do
something.

❑ A program is a set of instructions instructing a


computer to do specific tasks.

❑ “Software” is a generic term used to describe


computer programs. Scripts, applications, programs
and a set of instructions are all terms often used to
describe software.
Software categories
• Includes device drivers, operating systems (OSs), compilers, disk
formatters, text editors and utilities helping the computer to operate
System more efficiently.
software • System software serves as a base for application software.
• It is also responsible for managing hardware components.

• It is a set of tools to aid developers in writing programs.


Programming • The various tools available are compilers, linkers, debuggers,
interpreters and text editors.
software • A programming language provides a way for a programmer to express a
task so that it could be understood and executed by a computer.

Application • It is intended to perform certain tasks.


• Examples of application software include office suites, gaming
software applications, database systems and educational software.
What could possibly go wrong?

❑ We must communicate very precisely when we write Python code.

❑ The smallest deviation or mistake will cause Python to give up looking at your program.

❑ Beginning programmers often take the fact that Python leaves no room for errors.

Python is just a tool. It has looked at what you typed, and it simply
cannot understand what you have entered.
Program errors

Syntax errors
Logic errors
Semantic errors
Runtime errors
Syntax errors
❑ These are the first errors you will make and the easiest to fix.
❑ A syntax error means that you have violated the “grammar” rules of Python.
➢ Common Python syntax errors include:
➢leaving out a keyword
➢putting a keyword in the wrong place
➢leaving out a symbol, such as a colon, comma or brackets
➢misspelling a keyword
➢incorrect indentation
➢empty block
Logic errors
❑ A logic error is when your program has good syntax but there is a mistake in the order of the statements or perhaps a mistake in
how the statements relate to one another.

❑ A good example of a logic error might be, “take a drink from your water bottle, put it in your backpack, walk to the library, and
then put the top back on the bottle.”

Sum = 0 Sum = 0
N=1 N=1

While N <= 100 do Not in correct While N <= 100 do


order
N = N +1 Sum = Sum + N
Sum = Sum + N N = N +1

Print Sum Print Sum


End End
Semantic errors
❑ A semantic error is when your description of the steps to take is syntactically perfect and in the right
order, but there is simply a mistake in the program.
➢using the wrong variable name
➢using integer division instead of floating-point division
➢getting operator precedence wrong

Sum = 0 Sum = 0
N=1 N=1
Not the right
While N <= 100 do operator While N <= 100 do
Sum = Sum * N Sum = Sum + N
N = N +1 N = N +1

Print Sum Print Sum


End End
Runtime errors

➢If a program is syntactically correct – that is, free of syntax errors – it will be
run by the Python interpreter. However, the program may exit unexpectedly
during execution if it encounters a runtime error – a problem which was not
detected when the program was parsed, but is only revealed when a particular
line is executed.
➢ Some examples of Python runtime errors:
➢division by zero
➢performing an operation on incompatible types
➢using an identifier which has not been defined
➢accessing a list element, dictionary value or object attribute which doesn’t exist
➢trying to access a file which doesn’t exist
Again

In all three types of errors, Python is merely trying


its hardest to do exactly what you have asked.
Meet Python
❑ Python is a high-level, interpreted, interactive and object-oriented scripting language.

❑ It is designed to be highly readable.

❑ It uses English keywords.

❑ Broadly, Python is used to build applications and websites, and is used by companies like NASA,
Google, Facebook.

❑ Python is a great general-purpose language that can be used to write quick and simple programs.
Python features
❑ Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
❑ Easy-to-maintain: Python's source code is fairly easy-to-maintain.
❑ A broad standard library: Python's bulk of the library is very portable and cross-platform compatible
on UNIX, Windows, and Macintosh.
❑ Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
❑ Integration with other languages: It can be easily integrated with C, C++, COM, ActiveX, CORBA,
and Java.
❑ Python is a Beginner's Language: Python is a great language for the beginner-level programmers and
supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
❑ Python is OPEN SOURCE language: similarly, to Java, everyone can edit the python language. In
contrast, Visual basic is not open for edit.
Python Modes

• You write commands and


Interactive get them run, command by you
mode command.

Script • You write commands in a


script file and execute them all
mode at Once.
Chapter 2

Variables, expressions, and


statements
Values and types

❑ A value is one of the basic things a program works with, like a letter or a number.

❑ Examples of values are: 1, 2, and “Hello, World!”

❑ These values belong to different types: 2 is an integer, and “Hello, World!” is a string, so
called because it contains a “string” of letters.

❑ You (and the interpreter) can identify strings because they are enclosed in quotation marks.
Values and types

❑ If you are not sure what type a value has, the interpreter can tell you.
Variables
❑ One of the most powerful features of a programming language is the ability to
manipulate variables.

❑ A variable is a name that refers to a value.

❑ An assignment statement creates new variables and gives them values


Variables
❑ To display the value of a variable, you can use a print statement:

❑ The type of a variable is the type of the value it refers to.


Variables naming rules in Python
Variable names and keywords

➢If you give a variable an illegal name, you get a syntax error:
Statements
❑ A statement is a unit of code that the Python interpreter can execute.
❑ We have seen two kinds of statements: print being an expression statement and assignment.
❑ When you type a statement in interactive mode, the interpreter executes it and displays the
result, if there is one.
❑ A script usually contains a sequence of statements.
❑ If there is more than one statement, the results appear one at a time as the statements
execute.
Operators and operands
❑ Operators are special symbols that represent computations like addition and
multiplication.

❑ The values the operator is applied to are called operands.

❑ The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and


exponentiation.
Expressions
❑ An expression is a combination of values, variables, and operators.

❑ A value all by itself is considered an expression, and so is a variable, so the following are
all legal expressions.
Expressions
❑ If you type an expression in interactive mode, the interpreter evaluates it and displays the
result:

❑ But in a script, an expression all by itself doesn’t do anything! This is a common source of
confusion for beginners.
Computer Applications in Modern
Information Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Lecture 10
Math operators
Operator Sign Example Output

Add + 5+3 8

Subtraction - 5-3 2

Multiplication * 5*3 15

Division / 5/3 1.6666666666667

Floor division (quotient) // 5//3 1


Remainder (Mod) % 5%3 2

Power ** 5**3 125


Order of operations
❑ If you do not use parentheses, you need to know that the math
operators are executed according to their order of importance as
mentioned below:
➢Brackets.

➢Exponents and roots.

➢Multiplication and division.

➢Addition and subtraction.


Evaluating a mathematical expression
❑ Assume the programmer has written the expression:

❑ The programmer uses the following values to evaluate the


expression:
Evaluating a mathematical expression
String operations
❑ The + operator works with strings.

❑ It performs concatenation, which means joining the strings by


linking them end to end. For example:
Asking the user for input
❑ Sometimes we would like to take the value for a variable from the user via their
keyboard.

❑ Python provides a built-in function called input that gets input from the keyboard.

❑ When the user presses Enter, the program resumes and input returns what the user
typed as a string.
Comments
❑ Formal languages are dense, and it is often difficult to look at a piece of code and
figure out what it is doing, or why.

❑ It is a good idea to add notes to your programs to explain in natural language what
the program is doing.

❑ These notes are called comments, and in Python they start with the # symbol.

❑ Everything from the # to the end of the line is ignored; it has no effect on the program.
Chapter 3
Conditional execution
Boolean expressions
❑ A boolean expression is an expression that is either true or false.

❑ The following examples use the operator ==, which compares two operands and
produces True if they are equal and False otherwise:

❑ True and False are special values that belong to the class bool; they are not strings:
Python comparison operators
❑ x != y # x is not equal to y

❑ x>y # x is greater than y

❑ x<y # x is less than y

❑ x >= y # x is greater than or equal to y

❑ x <= y # x is less than or equal to y

❑ x is y # x is the same as y

❑ x is not y # x is not the same as y


Logical operators

Operator Description Example


and Returns True if both x > 5 and x < 10
statements are true
or Returns True if one of the x > 5 or x < 4
statements is true
not Reverse the result, returns not(x > 5 and x < 10)
False if the result is true
not Operator
and Operator
or Operator
Evaluating a logical expression
❑ Assume the programmer has written the expression:

❑ The programmer uses the following values to evaluate the expression:


Evaluating a relational and logical operators
❑ Assume the programmer has written the expression:

❑ The programmer uses the following values to evaluate the expression:


Conditional execution
❑ Conditional statements give us the ability to check conditions and change the behavior
of the program accordingly. The simplest form is the if statement:
Examples of conditional execution
Examples of code Output
x=5
if x ==5: equals 5
print "equals 5"
if x > 4:
greater than 4
print "greater than 4"
if x > = 5:
greater than or equals 5
print "greater than or equals 5"
if x < 6:
less than 6
print "less than 6"
if x < = 5:
less than or equals 5
print "less than or equals 5"
if x != 6:
not equal 6
print "not equal 6"
Alternative execution
❑ A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
Chained conditionals
❑ Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional:
Nested conditionals
❑ One conditional can also be nested within another. We could have written the three-
branch example like this:
Computer Applications in Modern Information
Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Lecture 11: Functions
Chapter 4
Functions
Function
❑ In the context of programming, a function is a named sequence of statements
that performs a computation or a specific task.

❑ When you define a function, you specify the name and the sequence of
statements.

❑ Later, you can “call” the function by name.


Functions

Built-in • They are those that are already


defined in Python libraries and
functions we can call them directly.

• They are those that we define


User defined ourselves in our program and
functions then call them wherever we
want.
Function calls
❑ The name of the function in this example is type.

❑ The expression in parentheses is called the argument of the function.


The argument is a value or variable that we are passing into the
function as input to the function.

❑ It is common to say that a function “takes” an argument and


“returns” a result.
argument
❑ The result is called the return value.

name result
Built-in functions
❑ Python provides a number of important built-in functions that we can use without needing to
provide the function definition.

❑ The creators of Python wrote a set of functions to solve common problems and included them in
Python for us to use.

❑ Example: the max and min functions give us the largest and smallest values in a list,
respectively:

❑ You should treat the names of built-in functions as reserved words (i.e., avoid using “max” as a
variable name).
Built-in functions: Examples
❑ max: returns the maximum of a list of arguments. max(2,5,7) -> 7
❑ min: returns the minimum of a list of arguments. max(2,5,7) -> 2
❑ Type-conversion functions:
▪ int(): returns an integer. int(3.5) returns 3, int(“5”) returns 5
▪ float(): returns a float. float(4) returns 4.0 , float(“6.5”) returns 6.5
▪ str(): returns a string. str(4) returns ”4” , str (4.5) returns “4.5”
▪ bool(): returns a Boolean:
▪ bool (any non-zero number) returns True,
▪ bool(0) returns False , bool(5) returns True
❑ Input/Output:
▪ input(msg): prints a message (msg) and accepts an input from the keyboard
▪ print(msg): print a message (msg) to the user
Math functions
❑ Python has a math module that provides most of the familiar
mathematical functions.

❑ Before we can use the module, we have to import it first:

❑ This statement creates a module object named math.


Functions in a module
❑ The module object contains the functions and variables defined in the module.

❑ To access one of the functions, you have to specify the name of the module and the name of the function,
separated by a dot (also known as a period).

❑ This format is called dot notation.


Adding new functions
❑ So far, we have only been using the functions that come with Python,
but it is also possible to add new functions (user-defined function).

❑ A function definition specifies the name of a new function and the


sequence of statements that execute when the function is called.

❑ Once we define a function, we can reuse the function over and over
throughout our program.
Adding new functions
def function_name(arguments):
statements to execute when the function is called
return return_value

❑ def is a keyword we use to define a function.


❑ function_name: the name of the function. Function names follow the same rules of variable names
❑ arguments (optional) a function may accept zero, one, or more arguments (parameters).
❑ Use empty parentheses () after the function name if it has no arguments.
Example: def do_something():
❑ return (optional): a function may or may not return a value when called.
❑ Function definition generates no output, the function executes only when it’s called.
❑ A function is defined once, but can be called many times in the same script/program.
Example (1): no arguments, no return value

❑ Function name: print_hello

❑ No arguments, empty parenthesis: print_hello()

❑ No return value: no return keyword

❑ When the function is called, it prints the string ‘Good morning Feps’ one time.
Example (2): with arguments, no return value

❑ Function name: by_5

❑ With one argument: x

❑ No return value: no return keyword

❑ Function definition generates no output.

❑ When the function is called, it accepts one argument ,x, and prints the value x*5.

❑ In this example, we called the function twice: one time with argument 3, and another with 2.
Example (3): with arguments, and return value

❑ Function name: my_avg

❑ With two arguments: x and y

❑ With return value: returns the average of x and y

❑ When the function is called, it accepts two arguments ,x and y, and returns their average.

❑ In this example, we called the function and assigned its return value to the variable result, then
we printed result.
Exercise:

1- Define a function is_even that accepts a positive integer argument, x, and prints “Even” if
x is even or “Odd” if x is odd.

2- Use this function to print whether these three number 20,25,30 are even or odd
Solution:
Why functions?
❑ Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read, understand, and debug.

❑ Functions can make a program smaller by eliminating repetitive code. Later, if


you make a change, you only have to make it in one place.

❑ Dividing a long program into functions allows you to debug the parts one at a
time.

❑ Well-designed functions are often useful for many programs. Once you write
and debug one, you can reuse it.
Computer Applications in Modern Information Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 12
Chapter 5
Iteration
Updating variables

A common pattern in assignment statements is an assignment statement that updates a


variable, where the new value of the variable depends on the old.

x=x+1
This means “get the current value of x, add 1, and
then update x with the new value.”

 If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side
before it assigns a value to x:
 >>> x = x + 1
 NameError: name 'x' is not defined
Updating variables
 Before you can update a variable, you have to initialize it, usually
with a simple assignment:

 Updating a variable by adding 1 is called an increment; subtracting


1 is called a decrement.
The while statement

Repeating identical or similar tasks without making errors is something


that computers do well and people do poorly.
A "While" Loop is used to repeat a specific block of code an unknown
number of times, until a condition is met.
 More formally, here is the flow of execution for a while statement:

1. Evaluate the condition, yielding True or False.

2. If the condition is false, exit the while statement and continue


execution at the next statement.

3. If the condition is true, execute the body and then go back to step 1.
while statement example

“While n is greater than 0, display the value of n and then reduce the value of n by 1.

When you get to 0, exit the while statement and display the word “Hello Feps”
Looping
 This type of flow is called a loop because the third step loops back around to
the top.

 We call each time we execute the body of the loop an iteration.

 For the above loop, we would say, “It had five iterations”, which means that
the body of the loop was executed five times.

 Loops allows us to repeat a single (or several) lines of code over and over
again. This allows us to "write once" and then "execute many times"
Infinite loops
 The body of the loop should change the value of one or more
variables so that eventually the condition becomes false and the loop
terminates.

 We call the variable that changes each time the loop executes and
controls when the loop finishes the iteration variable.

 If there is no iteration variable, the loop will repeat forever, resulting


in an infinite loop.
Breaking infinite loops
 The loop condition is True, which is always true, so the loop runs
infinitely without stopping.
Breaking infinite loops

 You can add a break statement, so the loop runs repeatedly until it hits the break statement. The break
statement ends the current loop and jumps to the statement immediately following the loop
Definite loops using for
 Sometimes we want to loop through a set of things such as a list of
words, the lines in a file, or a list of numbers.
We can write a loop to run the loop once for each of the items in a
set using the Python for construct
These loops are called "definite loops" because they execute an
exact number of times
 We call the while statement an indefinite loop because it simply loops
until some condition becomes False.
for loop example

 The variable friends is a list of three strings and the for loop goes through the list and
executes the body once for each of the three strings in the list.
 It goes like this: “Run the statements in the body of the for loop once for each friend in the
set named friends.”
for loop example

 Looking at the for loop, for and in are reserved Python keywords.

 friend is the iteration variable for the for loop.

 The variable friend changes for each iteration of the loop and controls when the for loop
completes.

 The iteration variable steps successively through the three strings stored in the friends
variable.
Loop patterns
 Often we use a for or while loop to go through a list of items or the
contents of a file and we are looking for something such as the largest or
smallest value of the data we scan through.

 These loops are generally constructed by:


Initializing one or more variables before the loop starts.

Performing some computation on each item in the loop body, possibly changing
the variables in the body of the loop.

Looking at the resulting variables when the loop completes.


Counting loops
 For example, to count the number of items in a list:

We set the variable count to zero before the loop starts, then we write a for loop to run
through the list of numbers.

Our iteration variable is named itervar.

In the body of the loop, we add 1 to the current value of count for each of the values in
the list.
Summing loops
 A loop that computes the total of a set of numbers:

 Before the loop starts total is zero because we have not yet seen any
values.

 During the loop total is the running total, and at the end of the loop total
is the overall total of all the values in the list.
Maximum loops
 To find the largest value in a list or sequence:

 When the program executes, the output is as follows:


The variable largest is best thought of as the “largest
value we have seen so far”. Before the loop, we set
largest to the constant None.
None is a special constant value which we can store
in a variable to mark the variable as “empty”.
Minimum loops
 To find the smallest value in a list or sequence:

 When the program executes, the output is as follows:


Computer Applications in Modern Information
Societies II (C201)

Introduction to Programming
(Using Python)
Lecture 13: Strings
Chapter 6
Strings
A string is a sequence
❑ A string is a sequence of characters.
➢Square brackets [ ] can be used to access elements of the string
>>> fruit="banana"
>>> print (fruit[0])
b
>>>

• Remember that the first character has the position 0


• The second statement extracts the character at index position 1 from
the fruit variable and assigns it to the letter variable.
A string is a sequence
❑ The expression in brackets is called an index. The index indicates
which character in the sequence you want.

Note:
• The value of the index has to be an integer.
• You will get a python error if you attempt to index beyond the end of a string.
Getting the length of a string using len
❑ len is a built-in function that returns the number of characters in a string:

❑ To get the last letter of a string, if you tempted to try something like this:

➢The reason for the IndexError is that there is no letter in “banana” with the
index 6. Since we started counting at zero, the six letters are numbered 0 to 5.
Getting the length of a string using len function

❑ To get the last character, you have to subtract 1 from length:


❑ Alternatively, you can use negative indices, which count backward from the end of
the string.
❑ The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and
so on.
Traversal through a string with a loop
❑ A lot of computations involve processing a string one character at a time.

❑ Often they start at the beginning, select each character in turn, do something to it,
and continue until the end. This pattern of processing is called a traversal.

❑ One way to write a traversal is with a while loop:

This loop traverses the string and displays each letter on a line by itself.
Traversal through a string with a for loop
❑ Another (and better) way to write a traversal is with a for loop:

❑ Each time through the loop, the next character in the string is assigned to the
variable char.

❑ The loop continues until no characters are left.


String slices
❑ A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:

❑ s[n:m] - this operator returns the part of the string from the “n-th” character to
the “m-th” character, including the first but excluding the last.
Looping and counting
❑ The following program counts the number of times the letter “a” appears in a string:

❑ This program demonstrates another pattern of computation called a counter.

❑ The variable count is initialized to 0 and then incremented each time an “a” is
found. When the loop exits, count contains the result: the total number of a’s.
The in operator
❑ The word in is a boolean operator that takes two strings and returns True if the
first appears as a substring in the second:
String comparison
❑ The comparison operators work on strings. To see if two strings are equal:

❑ In Python, all the uppercase letters come before the lowercase letters, and all
numbers come before letters. (“Ahmed” < “zyad”)
String methods
❑ Strings are an example of Python objects. An object contains both data (the actual string
itself) and methods, which are effectively functions that are built into the object and are
available to any instance of the object.
❑ Python has a function called dir which lists the methods available for an object.
Useful methods
Searching strings using find method
❑ find is a string method that returns the
position of one string within another.

❑ find method can find substrings as well as characters:

❑ find can take a second argument which is the index


where it should start:

❑ If the first string is not found in the second,


find will return -1
Parsing strings
❑ String parsing means looking into a string and extract some substring.

❑ For example, if we have a file with similar lines/strings like this one:

“From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008”

❑ And we want to extract (parse) the part of website (uct.ac.za) out of this string.

❑ We can do this by using the find method and string slicing.


Extracting “uct.ac.za” From “From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008”

1. Find the position of the at-sign “@” .


2. Find the position of the first space after the at-sign.
3. Use string slicing to extract the portion of the string which we are looking for.

Exercise: Can you write the code to extract the year? (which is 2008 in this example)
Exercise: Can you write the code to extract the year? (which is 2008 in this example)

“From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008”


➢The year is a 4-digit number at the end of the string
➢First solution:
>>> data[-4:len(data)]
'2008‘
➢Second solution (simpler):
>>> data[-4: ]
'2008'
What is the output?

data=“From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008”


F r om s t e p h e n . m a r q u a r d @u c t . a c . z a Sa t J a n 5 0 9: 1 4: 1 6 2008

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

data[0:4]? 'From'
data[5:]? 'stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
data[:5]? 'From '
data[:]? 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
data[-4:-2]? '20'
data[-2:-4]? '' The position of the second argument must be after the second one from the left
help in Python
Computer Applications in Modern Information
Societies II
C201 – 2021

Introduction to Programming
(Using Python)
Lecture 14
Chapter 8
Lists
A list is a sequence
❑ Like a string, a list is a sequence of values.

❑ In a string, the values are characters; in a list, they can be any type.

❑ The values in list are called elements or sometimes items.

❑ There are several ways to create a new list; the simplest is to enclose
the elements in square brackets (“[" and “]”):

[10, 20, 30, 40]

['crunchy frog', 'ram bladder', 'lark vomit’]

['spam', 2.0, 5, [10, 20]]


A list is a sequence
❑ A list within another list is nested.

❑ A list that contains no elements is called an empty list; you can create
one with empty brackets, [].
Lists are mutable
❑ The syntax for accessing the elements of a list is the same as for
accessing the characters of a string: the bracket operator.

❑ The expression inside the brackets specifies the index. Remember


that the indices start at 0:
Lists are mutable
❑ Unlike strings, lists are mutable (changeable) because you can change
the order of items in a list or reassign an item in a list.

❑ When the bracket operator appears on the left side of an


assignment, it identifies the element of the list that will be assigned.
Lists are mutable
❑ You can think of a list as a relationship between indices and
elements.
❑ This relationship is called a mapping; each index “maps to” one of the
elements.
❑ List indices work the same way as string indices: ‘Cheddar’ ‘Edam’ ‘Gouda’

[0] [1] [2]


❑ Any integer expression can be used as an index. [-3] [-2] [-1]

❑ If you try to read or write an element that does not exist, you get an
IndexError.

❑ If an index has a negative value, it counts backward from the end of the list.
Lists are mutable
❑ The in operator also works on lists.
Traversing a list
❑ The most common way to traverse the elements of a list is with a for
loop.

❑ The syntax is the same as for strings:

❑ This works well if you only need to read the elements of the list.
Traversing a list
❑ If you want to write or update the elements, you need the indices. A common way to do that is
to combine the functions range( ) and len( ):

This loop traverses the list and updates each element. len returns the number of elements in the list.
range returns a list of indices from 0 to n − 1, where n is the length of the list. Each time through
the loop, i gets the index of the next element. The assignment statement in the body uses i to read
the old value of the element and to assign the new value.
List operations
❑ The + operator concatenates lists:
List slices
❑ The slice operator also works on lists:
List methods
❑ Python provides methods that operate on lists.

append( ) adds a new element to the end of a list:


List methods
extend( ) takes a list as an argument and appends all of the elements:
List methods
sort( ) arranges the elements of the list from low to high:
Deleting elements
If you don’t need the removed value, you can use the del operator:

If you know the element you want to remove (but not the index), you can
use remove( ):
Lists and functions
❑ There are a number of built-in functions that can be used on lists
that allow you to quickly look through a list without writing your own
loops:

❑ The sum() function only works when the list elements are numbers.
Computer Applications in Modern Information
Societies II (C201)

Introduction to Programming
(Using Python)
Lecture 15: Files(1)
Chapter 7
Files
Persistence
❑ So far, we have learned how to write programs and communicate our intentions to
the Central Processing Unit using conditional execution, functions, and iterations.

❑ We have learned how to create and use data structures in the Main Memory.

❑ But if you recall from our hardware architecture discussions, once the power is
turned off, anything stored in either the CPU or main memory is erased.
Persistence
❑ In this chapter, we start to work with
Secondary Memory (or files).

❑ Secondary memory is not erased when the


power is turned off.

❑ We will primarily focus on reading and


writing text files such as those we create in a
text editor.
Opening files
➢A text file can be thought of as a sequence of lines, much like a Python string can be
thought of as a sequence of characters.

❑ When we want to read or write a file, we first must open the file first.

❑ Opening the file communicates with your operating system, which knows where the
data for each file is stored.

❑ When you open a file, you ask the operating system to find the file by name (and
path) and to make sure the file exists.
Opening files

❑ This is done with the open() function


❑ open() returns a “file handle” - a variable used to perform operations on the file

handle = open(filename, mode)


fhand = open(‘mbox.txt', 'r')

❑ In this example, we open the file mbox.txt, which should be stored in the same
folder that you are in when you start Python.
Handles
❑ If the open is successful, the operating system returns a
file handle.

❑ The file handle is not the actual data contained in the


file, but instead it is a “handle” that we can use to read
the data.

❑ You are given a handle if the requested file exists and


you have the proper permissions to read the file.

❑ If the file does not exist, open() function will fail and you
will not get a handle to access the contents of the file.
Reading files: reading the whole file at once
❑ If the file is relatively small compared to the size of your main memory, you can read
the whole file into one string using the read() method on the file handle:
Reading files: reading the file line by line
❑ While the file handle does not contain the data for the file, it is quite easy to
construct a for loop to read through and count each of the lines in a file:

❑ We can use the file handle as the sequence in a for loop.


❑ Our for loop counts the number of lines in the file and prints this number.
Reading files
❑ When the file is read using a for loop in this manner, Python takes care of splitting
the data in the file into separate lines using the newline character (\n).

❑ Python reads each line through the newline and includes the newline as the last
character in the line variable for each iteration of the for loop.
Searching through a file
❑ When you are searching through data in
a file, it is a very common pattern to read
through a file, ignoring most of the lines
and only processing lines which meet
a particular condition.

❑ For example, if we wanted to read a file and only print out lines which start with the
prefix “From:”, we could use the string method startswith() to select only those
lines with the desired prefix.
Searching through a file
Searching through a file
❑ The output looks great since the only lines we are seeing are those which start with
“From:”, but why are we seeing the extra blank lines?
❑ This is due to that invisible newline character.
From: stephen.marquard@uct.ac.za\n
❑ Each of the lines ends with a newline, so the print \n
function prints the string in the variable line which From: louis@media.berkeley.edu\n
\n
includes a newline and then print adds another
From: zqian@umich.edu\n
newline, resulting in the double spacing effect we \n
see. From: rjlowe@iupui.edu\n
\n
❑ We could use line slicing to print all but the last ...
character.
❑ Use the rstrip method which strips whitespace
(e.g. space, tab, new line) from the right side of a
string (we have also lstrip and strip).
Searching through a file
Searching through a file
❑ We can use the find() string method to simulate a text editor search that finds lines
where the search string is anywhere in the line.

❑ Since find() looks for an occurrence of a string within another string and either
returns the position of the string or -1 if the string was not found, we can write the
following loop to show lines which contain the string “@uct.ac.za”:
Searching through a file
Letting the user choose the file name
❑ We really do not want to have to edit our Python code every time we want to process a
different file.
❑ It would be more usable to ask the user to enter the file name string each time the program
runs so they can use our program on different files without changing the Python code.
Computer Applications in Modern Information
Societies II (C201)

Introduction to Programming
(Using Python)
Lecture 16: Files(2)
Writing files
❑ To write a file, you have to open it with mode “w” as a second argument:

❑ If the file already exists, opening it in write mode clears out the old data and starts
fresh, so be careful!

❑ If the file doesn’t exist, a new one is created.


Writing files
❑ The write method of the file handle object puts data into the file, returning the
number of characters written.

❑ The default write mode is text for writing (and reading) strings.
Writing files
❑ Again, the file handle object keeps track of where it is, so if you call write again, it
adds the new data to the end.

❑ We must make sure to manage the ends of lines as we write to the file by explicitly
inserting the newline character when we want to end a line.

❑ The print statement automatically appends a newline, but the write method does not
add the newline automatically.
Closing files
❑ When you are done writing (or reading), you have to close the file to make sure that
the last bit of data is physically written to the disk so it will not be lost if the power
goes off.
Exercise:
❑ Write a Python program to do the following tasks:
1. Create a new file on the docs folder on the C drive (C:\docs), call it delme.txt
2. Write the following two lines into the file:
‘Hello there, this is the first line’
‘Hello again, this is the second line’
3. Close the file delme.txt
4. Open the file delme.txt in reading mode
5. Print the content of delme.txt
6. Copy all the content of delme.txt to a new file delme2.txt.
7. Close any open files before the program ends.
Solution:
CSV Files
❑ A CSV file (Comma Separated Values file) is a type of plain text file that uses specific
structure to arrange tabular data.
❑ The following sample file has 4 variables (UserName, Password, StudentName and
dateOfBirth), and 3 cases (students)
❑ Variables’ names (in the first line) and Values are separated by commas (,)
Reading CSV files using csv module
❑ Use the reader object in the csv module to read data from a CSV file (after we import
the module)
❑ The CSV file is opened as a text file with Python’s built-in open() function, which
returns a file handle. This handle is passed to the reader.
❑ The next example explains this.
Example:
Writing to CSV files:
❑ Use the writer object in the csv module to write data to a CSV file
❑ The CSV file is opened as a text file with Python’s built-in open() function in writing
mode, which returns a file handle. This handle is passed to the writer.
Computer Applications in Modern Information Societies II
C201 – Fall 2019

Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 16
Chapter 9
Dictionaries
Dictionaries
❑ Dictionaries are another example of a data structure. A dictionary is like a list,
but more general.

❑ In a list, the index positions have to be integers; in a dictionary, the indices can
be (almost) any type.
◼ List
◼ A linear collection of values that stay in order

◼ Lists index their entries based on the position in the list

◼ Dictionary
◼ A “bag” of values (no order), each with its own label
Dictionaries

❑A dictionary in Python is just like a dictionary in the real world. Python


Dictionary are defined into two elements Keys and Values.
✓Keys will be a single element
✓Values can be a list or list within a list, numbers, etc.

❑ You can think of a dictionary as a mapping between a set of indices (which


are called keys) and a set of values. Each key maps to a value.

❑ As an example, we’ll build a dictionary that maps from English to Spanish


words, so the keys and the values are all strings.
Dictionaries

❑ The function dict creates a new dictionary with no items.


❑ Note: Because dict is the name of a built-in function, you should avoid using it as a variable name.

❑ The curly brackets, {}, represent an empty dictionary.


❑ To add items to the dictionary, you can use square brackets:

This line creates an item that maps from the key 'one' to the value “uno”. If we print the dictionary
again, we see a key-value pair with a colon between the key and value:
Dictionaries

➢ This output format is also an input format.


➢ For example, you can create a new dictionary with three items.
Dictionaries
❑ The elements of a dictionary are never indexed with integer indices. Instead, you use the
keys to look up the corresponding values:

❑ If the key isn’t in the dictionary, you get an exception:


Dictionaries
❑ The len function works on dictionaries; it returns the number of key-value pairs:
Dictionaries
❑ The in operator works on dictionaries; it tells you whether something appears as a key in
the dictionary (appearing as a value is not good enough).

❑ To see whether something appears as a value in a dictionary, you can use the method
values( ), which returns the values as a list, and then use the in operator:


Chapter 10
Tuples
Tuples are immutable
❑ A tuple is a sequence of values much like a list.

❑ The values stored in a tuple can be any type, and they are indexed by integers.

❑ The important difference is that tuples are immutable.

❑ Although it is not necessary, it is common to enclose tuples in parentheses to help us


quickly identify tuples when we look at Python code:
Tuples are immutable
❑ Most list operators also work on tuples.

The bracket operator indexes an element:

The slice operator selects a range of elements:


Tuples are immutable
❑ But if you try to modify one of the elements of the tuple, you get an error:
Differences between “List, Tuple and Dictionary” data structures

List Tuple Dictionary

✓Ordered and ✓Ordered and ✓Unordered,


changeable unchangeable changeable
(mutable). (immutable). (mutable).
✓Brackets used to ✓Brackets used to ✓Brackets used to
represent: [] represent: () represent: {}
✓Allows duplicate ✓Allows duplicate ✓ No duplicate
members. members. members.
Lists and Tuples data structures
Differences between List, Tuple and Dictionary
Variable Scope
❑ A scope of a variable identifies where it can be accessed (to read or change its value).
❑ A variable can be classified into two types according to its scope:
▪ Local Variable: Initialized inside a function, and it’s accessible only inside its function.
You get a NameError if you try to use a local variable outside its function.
▪ Global Variable: Initialized outside functions, and it is accessible (for reading) anywhere in the program,
inside and outside functions.
Updating Global Variables

❑ A global variable can be read anywhere in the program.


❑ To change the value of a global variable inside a function, you have to re-define it inside this
function using the global keyword
Computer Applications in Modern Information
Societies II (C201)

Object-Oriented Programming in Python


Lecture 1
What is OOP?

▪ As programs get Bigger and more complex, it becomes increasingly important to


write code that is easy to understand.
▪ If you are working on a million-line program, you can never keep the entire
program in your mind at the same time. We need ways to break large programs
into multiple smaller pieces so that we have less to look at when solving a
problem, fix a bug, or add a new feature.
▪ Object oriented programming is a way to arrange your code so that you can zoom
into 50 lines of the code and understand it while ignoring the other 999,950 lines
of code for the moment.
▪ Object Oriented programming (OOP) is a way of programming that focuses on
using objects and classes to design and build applications.
Python is an Object-Oriented Programming Language
▪ Almost everything in Python is an object
1234 3.14159 “Hello” [1, 5, 7, 11, 13]
{“CA”: “California”, “MA”:”Massachusetts”}
▪ Each is an object, and every object has:
o A type
o An internal data representation
o A set of procedures (methods) for interaction with the object
▪ An object is an instance of a type (class)
o 1234 is an instance of an int
o “Hello” is an instance of a string
▪ In OOP, you can create your own types (classes) and objects
Procedural vs. Object Oriented Programming

▪ Procedural based programming is derived from structural programming based on


the concepts of functions/procedure/routines. It is easy to access and change the
data in procedural oriented programming.
▪ Object Oriented Programming (OOP) allows decomposition of a problem into a
number of units called objects and then build the data and functions around these
objects. It emphasis more on the data than procedure or functions. Also in OOP,
data is hidden and cannot be accessed by external procedure.
What is OOP?

➢Lets take an example to better understand OOP.


➢ If we need to program a chess game:
What is OOP?

➢We will need to program chess pieces: 4 knights, 4 Bishops, 8 Pawns, etc...

➢Each piece will need several variables to represent its state, like: variable position to
determinate its place on the chess board, another variable color (white or black), variable
captured (yes or no), function move() to describe how this piece move.
➢It will be easier to group similar pieces together into one class
➢So, we will have a class of Knights that contains all the variables and functions (methods)
needed by every Knight (object) to describe its state, each Knight will have different data
concerning these variables.
➢At the same way we will have a class of Bishops, another one for Pawns and etc...
What is OOP?

➢Classes and objects are the main aspects of object-oriented programming.


➢Other examples of classes and objects:

Class Objects

Fruits Apple
Banana
Mango

Class Objects

Car Volvo
Audi
Toyota
What is OOP?
What is OOP?

▪ So, a class is a template for creating objects [object constructor/Blueprint], and


an object is an instance of a class.
▪ Class Car can create many cars object
▪ When the individual object is created, it inherit all the variables and functions from
the class, the object belongs to.
The class is like a cookie cutter and the objects created using
the class are the cookies.
You don’t put frosting on the cookie cutter; you put frosting
on the cookies, and you can put different frosting on each
cookie.
What is OOP?

▪ Definition of object-oriented programming:


Object-oriented programming (OOP) is a computer programming model
that organizes software design around data, or objects, rather than functions
and logic.

An object can be defined as : a data field that has unique attributes and
behavior. It is a constructed instance of a class. An object contains all of
the attributes and methods that were defined by the class.
What is OOP?

▪ Methods are functions that are defined inside a class that describe the
behaviors of an object. Each method contained in class definitions starts with
a reference to an instance object.
▪ Attributes are defined in the class template and represent the state of an
object. Objects will have data stored in the attributes field. Class attributes
belong to the class itself.
What is OOP?

➢ Python provides us with many built-in objects. Consider the following example:
stuff = list()

stuff.append('python')

stuff.append('chuck')

stuff.sort()

print (stuff[0])

print (stuff.__getitem__(0))

print (list.__getitem__(stuff,0))

# Code: http://www.py4e.com/code3/party1.py

➢ The first line constructs an object of type list, the second and third lines calls the append()
method, the fourth line is calls the sort() method, and the fifth line retrieves the item at position 0.
The sixth line calls the __getitem__() method in the stuff list with a parameter of zero.
➢ print (stuff.__getitem__(0)) The seventh line is an even more verbose way of retrieving the 0th
item in the list. print (list.__getitem__(stuff,0)) In this code, we call the __getitem__ method in the
list class and pass the list and the item we want to retrieve from the list as parameters.
What is OOP?

➢The last three lines of the program are equivalent, but it is more convenient
to simply use the square bracket syntax to look up an item at a particular
position in a list. We can take a look at the capabilities of an object by
looking at the output of the dir() function:
➢ >>> stuff = list()
➢>>> dir(stuff)
➢ ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort'] >>>
Main Concepts of Object-Oriented Programming (OOPs)
Classes

▪ Definition Syntax: To create a class, use the keyword class

class ClassName:
# Statement-1
.
.
.
# Statement-N

▪ Example: Create a class named MyClass, with a property named x:

class MyClass:
x = 5
Classes

The pass Statement


▪ class definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass statement to avoid getting an error.

▪ Example
Objects

▪ The object is an entity that has a state and behavior associated with it.
▪ It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
▪ Integers, strings, floating-point numbers, even arrays, and dictionaries, are all
objects. More specifically, any single integer or any single string is an object.
▪ The number 12 is an object, the string “Hello, world” is an object, a list is an object
that can hold other objects, and so on.
▪ You’ve been using objects all along and may not even realize it.
An object consists of :

▪ State: It is represented by the attributes of an object. It also reflects the properties of


an object. (breed, age, or color of the dog)
▪ Behavior: It is represented by the methods of an object. It also reflects the response
of an object to other objects. (methods to show how a dog eats or sleeps)
▪ Identity: It gives a unique name to an object and enables one object to interact with
other objects. (the name of the dog)
Example: Creating an Object

▪ This will create an object named obj of the class Dog (as defined before).

▪ Example:

Use the class named MyClass to create an object named p1, and print the value of x

class MyClass:
x=5
p1 = MyClass()
print(p1.x)
The self
▪ self refers to the Current Object.
▪ Class methods must have an extra first parameter in the method definition.
▪ We do not give a value for this parameter when we call the method, Python provides it.
▪ If we have a method that takes no arguments, then we still have to have one argument.
▪ When we call a method of this object as myobject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this
is all the special self is about.

Note: It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class
The __init__ method (the constructor)

▪ The __init__ method is called the constructor.


▪ It is run as soon as an object of a class is instantiated (when creating an object)
▪ The method is useful to do any initialization you want to do with your object.

Note: The __init__() function is called automatically every time the class is being used to create a new object.
Object Methods

➢ Objects can also contain methods. Methods in objects are functions that belong
to the object.
➢ Let us create a method in the Person class:

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
Modify Object Properties
Example
Computer Applications in Modern Information
Societies II (C201)

Object-Oriented Programming in Python


Lecture 2
4 Pillars of Object-Oriented Programming

Encapsulatio
n

Abstraction OOP Inheritance

Polymorphis
m
Inheritance
 Inheritance is the capability of one class to derive or inherit the properties from
another class.
 The class that derives properties is called the derived class or child class and the
class from which the properties are being derived is called the base class or parent
class.
 The benefits of inheritance are:
o It represents real-world relationships well.
o It provides the reusability of a code. We don’t have to write the same code again
and again. Also, it allows us to add more features to a class without modifying it.
o It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.
Inheritance
Example: Inheritance in Python
Polymorphism
 Polymorphism simply means having many forms.
 The details() method in the previous example is an example of polymorphism
Polymorphism
Polymorphism
 For example, if we have a parent class Animal, having 2 child classes: cats and dogs.
 Class Animal has a method sound() that describe an animal sound.
 The 2 classes cats and dogs inherit this method from the parent class Animal.
 The method sound() will be redefined (or overridden) in child class cats, by providing it new parameters
to make the sound of the cat.
 The same overriding procedure will be done at the child class dogs to make the sound of the dog.
Example: Polymorphism in Python
Encapsulation
 Encapsulation is one of the fundamental concepts in object-oriented programming.
 It describes the idea of wrapping data and the methods that work on data within one
unit.
 This puts restrictions on accessing variables and methods directly and can prevent
the accidental modification of data.
 To prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variables.
 A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Encapsulation
Example: Encapsulation in Python
Abstraction

This property allows us to hide the details and expose only the essential features of an
object.

Abstraction: Objects only reveal internal mechanisms that are relevant for the use of other
objects, hiding any unnecessary implementation code.

 Object shows only essential attributes and hides unnecessary information.

 This help in reducing programming complexity and efforts

 For example, in a car, we must know some attributes like the temperature of the car, the
quantity of fuel existing, the speed of the car , also, we must know how to use brakes,
steering wheel etc..., without knowing how these things work in details.
Benefits of OOP :

 Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and


collaborative development easier.

 Reusability. Code can be reused through inheritance, meaning a programmer does not have
to write the same code multiple times.

 Productivity. Programmers can construct new programs quicker through the use of multiple
libraries and reusable code.

 Easily upgradable and scalable. Programmers can implement system functionalities


independently.

 Security. Using encapsulation and abstraction, complex code is hidden and protected, so,
software maintenance is easier.

 Flexibility. Polymorphism enables a single function to adapt to the class it is placed in.
OOP Python Program

1- Create an Employee class with instance attributes and methods.

2- Create a child class GenericEmp (has not computational skills) that inherits all the
variables and methods from the Employee class, additionally, this child class has some
specific methods.
>>>class Employee:
def __init__(self, name, age, department, is_manager, rating, salary):
self.name=name
self.age=age
self.department=department
self.is_manager=is_manager
self.rating=rating #rating is between 1 to 5
self.salary=salary
def is_excellent(self):
if self.rating>=4.5:
return True
else:
return False
def bonus(self):
if self.age >=60:
self.salary+= 500
print("Salary will increase to: ", self.salary)
else:
print("Salary will not increase: ", self.salary)
>>>employee1=Employee("Islam",50,"Finance",True,5,10000)
>>> employee2=Employee("Ibrahim",60,"HR",False,3.5,5000)
>>>print(employee1.age, employee2.age, employee1.is_manager, employee2.department)
50 60 True HR
>>> print(employee1.is_excellent())
True
>>> print(employee2.is_excellent())
False
>>> employee1.bonus()
Salary will not increase: 10000
>>> employee2.bonus()
Salary will increase to: 5500
>>> class GenericEmp(Employee):
def is_excellent(self): # override the function
if self.rating >=3.5:
return True
else:
False
def Expyears (self, experience):
self.experience=experience
print (self.name , experience)
>>> ge1 = GenericEmp("Ahmed",45,"Production",False,4,3000)
>>> ge1.is_excellent()
True
>>>print (ge1.name)
Ahmed

You might also like