All Ssc2 Slides
All Ssc2 Slides
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: [email protected]
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
Introduction to programing
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
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
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
Dr Ghada Deghedi
2022-2023
Lecture 2
1
Problem Solving Models
2
Six-Steps Problem Solving Model
• Some problem-solving models can be highly
sophisticated and technical.
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.
7
Step One: Define 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:
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
13
Root cause analysis (RCA)
Steps Tools
Point of
Process
Cause
Mapping
Analysis
14
RCA Steps
15
1-The point of cause Analysis
16
The Process Map
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
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“
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
14
Evaluating Solutions Techniques
• Examples of techniques that can help in
evaluating solutions:
– Cost benefit analysis.
– Decision matrix.
Cost-Benefit Analysis (CBA)
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
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
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
6
Optimal approach
8
Step Five: Implement the Solution
Determine objectives.
– Who …
– By when
– Where
– How
Implement the plan
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.
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).
› 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).
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.
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
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
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
12
Algorithm Definition
• An algorithm can be defined as “a complete,
unambiguous, finite number of logical steps
for solving a specific problem “
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
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.
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
4
Defining actions in FindLargest algorithm
FindLargest refined
Generalization of FindLargest
Three constructs
Loop Design
Step3: I=2
Step4: While (I <= N) do
Step5: PROD = PROD* I
Step6: I=I+1
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
The sum is 22
15
Socio-Computing Department
Faculty of Economics and Political Science
Cairo University
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.
• These are particularly useful for small • These are useful for detailed
problems. representations of complicated programs.
5
Symbols used in Flowcharts
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.
8
General Rules for flowcharting
9
Flowcharts’ main structures
10
Decision )
Binary(structure
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
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
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
Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 8
Reference
Charles R. Severance
Introduction
Implementation phase
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
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.
When you first start, you will be both the programmer and the end user of
your programs.
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.
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.
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
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:
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.
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.
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.
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 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
Introduction to Programming
(Using Python)
Dr. Ghada Deghedi
Lecture 9
What is a program?
❑ 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
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
➢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
❑ 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
❑ A value is one of the basic things a program works with, like a letter or a number.
❑ 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.
➢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.
❑ 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
❑ 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 is y # x is the same as y
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.
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.
❑ 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).
❑ 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
❑ When the function is called, it prints the string ‘Good morning Feps’ one time.
Example (2): with arguments, no return value
❑ 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
❑ 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.
❑ 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
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:
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.
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.
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.
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.
Performing some computation on each item in the loop body, possibly changing
the variables in the body of the loop.
We set the variable count to zero before the loop starts, then we write a for loop to run
through the list of numbers.
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:
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
>>>
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
❑ 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.
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.
❑ 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:
❑ 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.
❑ For example, if we have a file with similar lines/strings like this one:
❑ And we want to extract (parse) the part of website (uct.ac.za) out of this string.
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)
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:]? '[email protected] Sat Jan 5 09:14:16 2008'
data[:5]? 'From '
data[:]? 'From [email protected] 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.
❑ There are several ways to create a new list; the simplest is to enclose
the elements in square brackets (“[" and “]”):
❑ 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.
❑ 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.
❑ 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.
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).
❑ 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
❑ 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.
❑ 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:
❑ 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: [email protected]\n
❑ Each of the lines ends with a newline, so the print \n
function prints the string in the variable line which From: [email protected]\n
\n
includes a newline and then print adds another
From: [email protected]\n
newline, resulting in the double spacing effect we \n
see. From: [email protected]\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!
❑ 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
◼ Dictionary
◼ A “bag” of values (no order), each with its own label
Dictionaries
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
❑ 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.
➢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?
Class Objects
Fruits Apple
Banana
Mango
Class Objects
Car Volvo
Audi
Toyota
What is OOP?
What is OOP?
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
class ClassName:
# Statement-1
.
.
.
# Statement-N
class MyClass:
x = 5
Classes
▪ 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 :
▪ 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)
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)
Encapsulatio
n
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.
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 :
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.
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
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