0% found this document useful (0 votes)
11 views

CF - Chapter-006 STU

cf

Uploaded by

aliza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CF - Chapter-006 STU

cf

Uploaded by

aliza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Chapter No 6 : Elementary Programming

C E – 119
Computing Fundamentals (CF)

Compiled By:

Sir Syed University of Engineering & Technology


Engr.Syed Atir Iftikhar
Computer Engineering Department [email protected]
University Road, Karachi-75300, PAKISTAN 1
CE - 119 : Computing Fundamentals (CF)
 Course Objectives:
 This course covers the concepts and fundamentals
of computing and programming. Topics includes
history, components of computers, hardware,
software, operating systems, database, networks,
number systems and logic gates. Also it includes
programming topics such as basic building blocks,
loop, decision making statements.

2
CE - 119 : Computing Fundamentals (CF)
 Course Learning Outcomes ( CLO )
CLO Level
Outcome Statement
No. *
Explain the fundamental knowledge and concepts about
1 computing infrastructure including hardware, software, C2
database and networks.
Applying and Implementing number systems and logic
2 C3
gates.
Applying and Implementing problem solving skills and
3 solve problems incorporating the concept of C3
programming. 3
Books

 Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary
2. Introduction to Computers, Peter Norton, 6th Edition, McGraw-Hill
3. Introduction to Programming using Python, Daniel Liang
4. Turbo C Programming For The PC, Robert Lafore, Revised Edition

 Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning
2. Using Information Technology: A Practical Introduction to Computers
& Communications, Williams Sawyer, 9th Edition, McGraw-Hill
3. Introduction to Python, Paul Deitel, Harvey Deitel
4. Let Us C, Yashavant Kanetkar 4
Marks Distribution

 Total Marks ( Theory ) ___________ 100


 Mid Term ___________ 25
 Assignments + Quizzes + Presentation ___________ 25
 Semester Final Examination Paper ___________ 50

 Total Marks ( Laboratory ) ___________ 50


 Lab File ___________ 15
 Subject Project ___________ 15
 Lab Exam/Quiz ( Theory Teacher ) ___________ 20

 https://sites.google.com/view/muzammil2050

5
Course Instructors

 Muzammil Ahmad Khan [email protected]


Assistant Professor, CED
Room No: BS-04

 Atir Iftikhar [email protected]


Lecturer, CED
Room No: BT-05

6
CE – 119: Computing Fundamentals Chapter

Elementary Programming

Compiled By:
Engr.Syed Atir Iftikhar [email protected]
7
Motivations

 Suppose, for example, that you need to take out a


student loan. Given the loan amount, loan term, and
annual interest rate, can you write a program to
compute the monthly payment and total payment?

 This chapter shows you how to write programs like


this. Along the way, you learn the basic steps that go
into analyzing a problem, designing a solution, and
implementing the solution by creating a program.
8
Objectives
 To write programs that perform simple computations.
 To obtain input from a program’s user by using the
input function.
 To use identifiers to name variables.
 To assign data to variables.
 To define named constants.
 To use the operators +, -, *, /, //, %, and **.
 To write and evaluate numeric expressions.
 To use augmented assignment operators to simplify coding.
 To perform numeric type conversion and rounding with the
int and round functions.
 To obtain the current system time by using time.time().
 To describe the software development process and apply it to
develop the loan payment program.
9
Introducing Programming with an Example

 Program 2.1 Computing the Area of a Circle


 This program computes the area of the Circle.

10
Program 2.1 ComputingtheAreaofaCircle.py

# Assign a value to radius

radius = 20

# Compute area

area = radius * radius * 3.14159

# Display results

print("The area for the circle of radius", radius, "is", area)

Output:
The area for the circle of radius 20 is 1256.636
11
str ( ) function
 The str ( ) function converts values to a string form so they
can be combined with other strings.

 The str ( ) function returns the string version of the given


object.

 For numbers, the standard operators, +, /, * work in the


usual way.

 The str ( ) function converts the specified value into a


string.
12
str ( ) function
 # Python program to demonstrate strings
s = str("GFG")
print(s)
 Output:
GFG
 # Python program to demonstrate strings
num = 100
a = str(num)
print(a)
 Output:
100 13
Program 2.2 ComputingtheAreaofaCircle.py

# Assign a radius

radius = 20

# Compute area

area = radius * radius * 3.14159

# Display results

print("Area of the circle of radius " + str(radius) + " is "+str(area))

Output:
The area for the circle of radius 20 is 1256.636
14
animation
Trace a Program Execution
Assign 20 to
# Assign a radius radius
radius = 20 # radius is now 20
radius 20
# Compute area
area = radius * radius * 3.14159
# Display results
print("The area for the circle of radius " +
str(radius) + " is " + str(area))

15
animation
Trace a Program Execution
Assign result to
# Assign a radius area
radius = 20 # radius is now 20
radius 20
# Compute area
area = radius * radius * 3.14159 area 1256.636

# Display results
print("The area for the circle of radius“,
radius, " is "area)

16
animation
Trace a Program Execution
print a message to
# Assign a radius the console

radius = 20 # radius is now 20


radius 20
# Compute area
area = radius * radius * 3.14159 area 1256.636

# Display results
print("The area for the circle of radius",
radius, "is", area)

17
Reading Input from the Console
1. Use the input function
variable = input("Enter a string: ")

2. Use the eval function

var = eval(stringVariable)

eval("51 + (54 * (3 + 2))") returns 321.

18
Reading Input from the Console
 eval is a built-in- function used in python, eval
function parses the expression argument and
evaluates it as a python expression.

 In simple words, the eval function evaluates the


“String” like a python expression and returns the
result as an integer.

 The syntax of the eval function is as shown below:

eval(expression, [globals[, locals]])


19
What is the difference between the input() and eval()?

 Eval evaluates a piece of code. input gets a string from


user input. Therefore:
 Eval(input()) evaluates whatever the user enters. If the
user enters 123, the result will be a number, if they enter
"foo" it will be a string, if they enter ?wrfs, it will raise an
error.
 Eval("input()") evaluates the string "input()", which causes
Python to execute the input function. This asks the user for
a string (and nothing else), which is while 123 will be the
string "123", ?wrfs will be the string "?wrfs", and "foo"
will be the string '"foo"' (!).
 Eval(eval("input()")) is exactly identical to eval(input()).

20
Program 2.3
# Prompt the user to enter a radius

radius = eval(input("Enter a value for radius: "))

# Compute area

area = radius * radius * 3.14159

# Display results

print("The area for the circle of radius", radius, "is", area)

Output:
Enter a value for radius: 5.1
The area for the circle of radius 5.1 is 81.71275589999999 21
Program 2.4
# Prompt the user to enter three numbers

number1 = eval(input("Enter the first number: "))

number2 = eval(input("Enter the second number: "))

number3 = eval(input("Enter the third number: "))

# Compute average

average = (number1 + number2 + number3) / 3

# Display result

print("The average of", number1, number2, number3, "is", average)


22
Program 2.4
Output:
Enter the first number: 5
Enter the second number: 10
Enter the third number: 25
The average of 5 10 25 is 13.333333333333334

You can use the function eval to evaluate and convert it to a


numeric value. For example, eval("34.5") returns 34.5,
eval("345") returns 345,
eval("3 + 4") returns 7, and eval("51 + (54 * (3 + 2))") returns
321.
23
Escape Sequence
 Escape Sequences are used
Code Description
to signal an alternative
\’ Single Quote
interpretation of a series of
\” Double Quote
characters.
\\ Back Slash
 It interrupts the normal flow
\b Backspace
of output value.
 An escape character is a \n New Line

backslash \ followed by the \t Tab

character you want to insert. \r Carriage Return


Program ComputeExpression.py

print("Greetings \nSir")

print("Welcome to the world of \"Programming\"")

print("Have a \rnice day...")

Output:
Greetings
Sir
Welcome to the world of "Programming"
nice day...
25
Comments in Python
 Anything after a # is ignored by Python

 Why comment?
 Describe what is going to happen in a sequence of code
 Document who wrote the code or other ancillary
information
 Turn off a line of code - perhaps temporarily
Identifiers/Variable Names
 An identifier is a sequence of characters that
consists of letters, digits, underscores (_), and
asterisk (*).
 An identifier must start with a letter or an
underscore. It cannot start with a digit.
 An identifier cannot be a reserved word.
(See Appendix A, "Python Keywords," for a list of
reserved words.)
 Reserved words have special meanings in Python,
which we will later.
 An identifier can be of any length.
27
Python Variable Name Rules

 Must start with a letter or underscore _

 Must consist of letters and numbers and underscores

 Case Sensitive

 Good: spam eggs spam23 _speed

 Bad: 23spam #sign var.12

 Different: spam Spam SPAM


Python Variable Name - Tips
 Because Python is case sensitive, area, Area, and AREA are all different
identifiers.
 Descriptive identifiers make programs easy to read. Avoid using
abbreviations for identifiers. Using complete words is more descriptive.
For example, numberOfStudents is better than numStuds, numOfStuds,
or numOfStudents. We use descriptive names for complete programs in
the text. However, we will occasionally use variables names such as i, j, k,
x, and y in the code snippets for brevity. These names also provide a
generic tone to the code snippets.
 Uselowercase letters for variable names, as in radius and area. If a name
consists of several words, concatenate them into one, making the first word
lowercase and capitalizing the first letter of each subsequent word—
for example, numberOfStudents. This naming style is known as the
camelCase because the uppercase characters in the name resemble a
camel’s humps.
Reserved Words
 You can not use reserved words as variable names /
identifiers
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Variables
•A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later
statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
Program 2.5 Variables area.py

# Compute the first area


radius = 1.0
area = radius * radius * 3.14159
print("The area is", area, "for radius", radius)

# Compute the second area


radius = 2.0
area = radius * radius * 3.14159
print("The area is", area, "for radius", radius)
32
Program 2.5 Variables area.py

 Output

The area is 3.14159 for radius 1.0

The area is 12.56636 for radius 2.0

33
Program 2.6 Variables arithmetic.py

# Computation of Arithmetic Operations


num1 = 30
num2 = 20
num3 = 10
sum = num1+num2+num3
subtraction = num1-num2-num3
print("Addition is: ",sum)
print("Subtraction is:",subtraction)
34
Program 2.6 Variables arithmetic.py

 Output

Addition is: 60

Subtraction is: 0

35
Program 2.7 Variables arithmetic_input.py

# Computation of Arithmetic Operations


num1 = eval(input("Enter the first number: "))
num2 = eval(input("Enter the second number: "))
num3 = eval(input("Enter the third number: "))
sum = num1+num2+num3
subtraction = num1-num2-num3
print("Addition is: ",sum)
print("Subtraction is:",subtraction)
36
Program 2.7 Variables arithmetic_input.py

 Output

Enter the first number: 30

Enter the second number: 20

Enter the third number: 10

Addition is: 60

Subtraction is: 0

37
Program 2.8 Variables ERROR
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
num3 = input("Enter the third number: ")
sum = num1+num2+num3
print("Addition is: ",sum)
Output:
Enter the first number: 30
Enter the second number: 20
Enter the third number: 10
Addition is: 302010
38
ERROR
Expression
x=1 # Assign 1 to variable x
radius = 1.0 # Assign 1.0 to variable radius

# Assign the value of the expression to x


x = 5 * (3 / 2) + 3 * 2

x=y+1 # Assign the addition of y and 1 to x


area = radius * radius * 3.14159 # Compute area

39
Assignment Statements
 An assignment statement consists of an expression
on the right hand side and a variable to store the
result
 The statement for assigning a value to a variable is
called an assignment statement.
 In Python, the equal sign (=) is used as the
assignment operator. The syntax for assignment
statements is as follows:
variable = expression

X = 3.9 * x * ( 1 - x )
A variable is a memory location
x 0.6
used to store a value (0.6)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4

0.93
Right side is an expression.
Once expression is evaluated, the
result is placed in (assigned to) x.
A variable is a memory location used
to store a value. The value stored in
a variable can be updated by
replacing the old value (0.6) with a x 0.6 0.93
new value (0.93).

x = 3.9 * x * ( 1 - x )

0.93
Right side is an expression.
Once expression is evaluated, the
result is placed in (assigned to) the
variable on the left side (i.e. x).
Assignment Statements

x=1 # Assign 1 to x

x=x+1
Every variable has a scope. The scope of a
variable is the part of the program where the
i=j=k= 1 variable can be referenced

 Every variable has a scope. The scope of a variable


is the part of the program where the variable can be
referenced
43
Assignment Statements

44
Assignment Statements
 A variable must be assigned a value before it can be
used in an expression.
 For example,
interestRate = 0.05
interest = interestrate * 45
 This code is wrong, because …..

45
Assignment Statements
 For example,
interestRate = 0.05
interest = interestrate * 45
 This code is wrong, because interestRate is
assigned a value 0.05, but interestrate is
not defined.
 Python is case-sensitive. interestRate and
interestrate are two different
46
variables.
Simultaneous Assignment

var1, var2, ..., varn = exp1, exp2, ..., expn

x, y = y, x # Swap x with y

47
Simultaneous Assignment
 Swapping variable values is a common operation in programming and
simultaneous assignment is very useful to perform this operation.
 Consider two variables: x and y. How do you write the code to swap their
values? A common approach is to introduce a temporary variable as
follows:
>>> x = 1
>>> y = 2
>>> temp = x # Save x in a temp variable
>>> x = y # Assign the value in y to x
>>> y = temp # Assign the value in temp to y
 But you can simplify the task using the following statement to swap the
values of x and y.
>>> x, y = y, x # Swap x with y

48
Program 2.9 Variables
# Compute Average with Simultaneous Assignment

# Prompt the user to enter three numbers

number1, number2, number3 = eval(input(

"Enter three numbers separated by commas: "))

# Compute average

average = (number1 + number2 + number3) / 3

# Display result

print("The average of", number1, number2, number3 ,"is", average)


49
Program 2.9 Simultaneous Assignments

 Output

Enter three numbers separated by commas:


10,20,40

The average of 10 20 40 is 23.333333333333332

50
Named Constants
 The value of a variable may change during the
execution of a program, but a named constant or
simply constant represents permanent data that
never changes.
 Python does not have a special syntax for naming
constants. You can simply create a variable to denote
a constant.
 To distinguish a constant from a variable, use all
uppercase letters to name a constant.

51
Numerical Data Types

 integer: e.g., 3, 4

 float: e.g., 3.0, 4.0

52
Several Types of Numbers
 Numbers have two main types >>> xx = 1
 Integers are whole numbers: >>> type (xx)
-14, -2, 0, 1, 100, 401233 <class 'int'>
>>> temp = 98.6
 Floating Point Numbers have
>>> type(temp)
decimal parts: -2.5 , 0.0, 98.6,
< class 'float'>
14.0
>>> type(1)
 There are other number types - < class 'int'>
they are variations on float and >>> type(1.0)
integer < class 'float'>
>>>
Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Float Division 1 / 2 0.5

// Integer Division 1 // 2 0

** Exponentiation 4 ** 0.5 2.0

% Remainder 20 % 3 2

54
/ and // Operator
 The / operator performs a float division that results in a
floating number.
>>> 4 / 2
2.0
>>> 2 / 4
0.5
 The // operator performs an integer division; the result
is an integer, and any fractional part is truncated.
>>> 5 // 2
2
>>> 2 // 4
0
55
The % Operator

2 3 3 1 Quotient
3 7 4 12 8 26 Divisor 13 20 Dividend
6 12 24 13
1 0 2 7 Remainder

56
Remainder Operator
Remainder is very useful in programming. For example,
an even number % 2 is always 0 and an odd number % 2
is always 1. So you can use this property to determine
whether a number is even or odd. Suppose today is
Saturday and you and your friends are going to meet in
10 days. What day is in 10 days? You can find that day is
Tuesday using the following expression:

Saturday is the 6th day in a week


A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

57
Numeric Data Types
 How do we tell Python whether a number is an
integer or a float? A number that has a decimal point
is a float even if its fractional part is 0.
 For example, 1.0 is a float, but 1 is an integer. These
two numbers are stored differently in the computer.
 In the programming terminology, numbers such as
1.0 and 1 are called Literals.
 A Literal is a constant value that appears directly in
a program.
58
Problem: Displaying Time
 Write a program that obtains hours and minutes
from seconds.

59
Program 2.10 Displaying Time
# Prompt the user for input
seconds = eval(input("Enter an integer for seconds: "))

# Get minutes and remaining seconds


minutes = seconds // 60 # Find minutes in seconds
remainingSeconds = seconds % 60 # Seconds remaining

print(seconds, "seconds is", minutes,


"minutes and", remainingSeconds, "seconds")

60
Program 2.10 Displaying Time

 Output

Enter an integer for seconds: 110

110 seconds is 1 minutes and 50 seconds

61
Overflow
 When a variable is assigned a value that is too
large (in size) to be stored, it causes overflow.
For example, executing the following statement
causes overflow.

>>>245.0 ** 1000
OverflowError: 'Result too large'

62
Underflow
 When a floating-point number is too small (i.e., too
close to zero) to be stored, it causes underflow.
Python approximates it to zero. So normally you
should not be concerned with underflow.

63
Scientific Notation
 Floating-point literals can also be specified in
scientific notation, for example,

 1.23456e+2, same as 1.23456e2, is equivalent to


123.456, and

 1.23456e-2 is equivalent to 0.0123456.

 E (or e) represents an exponent and it can be either


in lowercase or uppercase.

64
Arithmetic Expressions

3  4 x 10( y  5)( a  b  c) 4 9 x
  9(  )
5 x x y

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

65
Order of Evaluation

 When we string operators together - Python must


know which one to do first

 This is called “operator precedence”

 Which operator “takes precedence” over the others

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
 Highest precedence rule to lowest precedence rule
 Parenthesis are always respected
 Exponentiation (raise to a power)
 Multiplication, Division, and Remainder
 Addition and Subtraction
Parenthesis
 Left to right Power
Multiplication
Addition
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print(x)
11 1+8/4*5
>>>
1+2*5
Parenthesis
Power 1 + 10
Multiplication
Addition 11
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print x
11 1+8/4*5
>>> Note 8/4 goes before 4*5 1+2*5
because of the left-right
rule.
1 + 10
Parenthesis
Power
Multiplication 11
Addition
Left to Right
Operator Precedence
 Remember the rules top to bottom
 When writing code - use parenthesis
 When writing code - keep mathematical expressions
simple enough that they are easy to understand
 Break long series of mathematical operations up to
make them more clear
Parenthesis
Power
Multiplication
Exam Question: x = 1 + 2 * 3 - 4 / 5 Addition
Left to Right
How to Evaluate an Expression
Though Python has its own way to evaluate an
expression behind the scene, the result of a Python
expression and its corresponding arithmetic expression
are the same. Therefore, you can safely apply the
arithmetic rule for evaluating a Python expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
71
Mixing Integer and Floating
 When you perform an operation where one operand
is an integer and the other operand is a floating
point the result is a floating point
 The integer is converted to a floating point before
the operation

>>> print (1 + 2 * 3 / 4.0 – 5)


-2.5
>>>
Augmented Assignment Operators
 The operators +, -, *, /, //, %, and ** can be combined with
the assignment operator (=) to form augmented assignment
operators.

 Python allows you to combine assignment and addition


operators using an augmented (or compound) assignment
operator.

 count = count + 1 can be written as count += 1

 The += operator is called the addition assignment operator.


73
Augmented Assignment Operators

Operator Example Equivalent


+= i += 8 i=i+8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i=i*8
/= i /= 8 i=i/8
%= i %= 8 i=i%8

74
Type Conversion and Rounding

datatype(value)
i.e., int(4.5) => 4
float(4) => 4.0
str(4) => “4”

round(4.6) => 5
round(4.5) => 4
75
Problem: Keeping Two Digits After
Decimal Points

 Write a program that displays the sales tax with


two digits after the decimal point.

76
Program 2.11 Sales Tax
# Prompt the user for input

purchaseAmount = eval(input("Enter purchase amount: "))

# Compute sales tax

tax = purchaseAmount * 0.06

# Display tax amount with two digits after decimal point

print("Sales tax is", int(tax * 100) / 100.0)


 Output
Enter purchase amount: 50
Sales tax is 3.0
77
Problem: Displaying Current Time
Write a program that displays current time in GMT
in the format hour:minute:second such as 1:45:19.
The time.time() function returns the current time in
seconds with millisecond precision since the midnight,
January 1, 1970 GMT. (1970 was the year when the
Unix operating system was formally introduced.)
You can use this function to obtain the current time,
and then compute the current second, minute, and hour
as follows. Elapsed
time
Time
Unix epoch Current time
01-01-1970 time.time()
00:00:00 GMT
78
Problem: Displaying Current Time
 time.time() returns 1285543663.205, which means 1285543663 seconds and
205 milliseconds.
 You can use this function to obtain the current time, and then compute the current
second, minute, and hour as follows.
1. 1. Obtain the current time (since midnight, January 1, 1970) by invoking
time.time() (for example, 1203183068.328).
2. Obtain the total seconds totalSeconds using the int function
(int(1203183068.328) 1203183068).
3. Compute the current second from totalSeconds % 60 (1203183068 seconds %
60 = 8, which is the current second).
4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60
(1203183068 seconds // 60 20053051 minutes).
5. Compute the current minute from totalMinutes % 60 (20053051 minutes % 60
31, which is the current minute).
6. Obtain the total hours totalHours by dividing totalMinutes by 60 (20053051
minutes // 60 334217 hours).
7. Compute the current hour from totalHours % 24 (334217 hours % 24 17,
which is the current hour).

79
Program 2.12 Show Current Time
import time

currentTime = time.time() # Get current time

totalSeconds = int(currentTime) # Obtain the total seconds since midnight, Jan 1, 1970

currentSecond = totalSeconds % 60 # Get the current second

totalMinutes = totalSeconds // 60 # Obtain the total minutes

currentMinute = totalMinutes % 60 # Compute the current minute in the hour

totalHours = totalMinutes // 60 # Obtain the total hours

currentHour = totalHours % 24 # Compute the current hour

print("Current time is", currentHour, ":", currentMinute, ":“, currentSecond, "GMT")

80
Program 2.12 Show Current Time

 Output

Current time is 19 : 0 : 10 GMT

81
Software Development Process
 The software development life cycle is a
multistage process that includes requirements
specification, analysis, design, implementation,
testing, deployment, and maintenance.
 Developing a software product is an engineering
process. Software products, no matter how large or
how small, have the same life cycle: requirements
specification, system analysis, system design,
implementation, testing, deployment, and
maintenance, as shown in following figure.
82
Software Development Process
Requirement
Specification

System
Analysis

System
Design

Implementation

Testing

Deployment

Maintenance

83
Requirement Specification
Requirement Specification is a
Requirement
Specification
formal process that seeks to
understand the problem and
System document in detail what the software
Analysis
system needs to do. This phase
System involves close interaction between
Design users and designers.

Implementation

Most of the examples in this book Testing


are simple, and their requirements
are clearly stated. In the real world, Deployment
however, problems are not well
defined. You need to study a
problem carefully to identify its Maintenance

requirements. 84
System Analysis
Requirement System Analysis seeks to analyze the
Specification
business process in terms of data flow,
System and to identify the system’s input and
Analysis output.
System
Design

Implementation

Testing
Part of the analysis entails modeling
the system’s behavior. The model is Deployment
intended to capture the essential
elements of the system and to define
Maintenance
services to the system.
85
System Design
Requirement System Design is the process of
Specification
designing the system’s components.
System
Analysis

System
Design

Implementation

Testing
This phase involves the use of many
levels of abstraction to decompose the
Deployment
problem into manageable components,
identify classes and interfaces, and
establish relationships among the Maintenance
classes and interfaces.
86
IPO
Requirement
Specification

System
Analysis Input, Process, Output

System
Design

Implementation

Testing

Deployment

The essence of system analysis and design is Maintenance


input, process, and output. This is called IPO.

87
Implementation
Requirement Implementation is the process
Specification of translating the system
System
design into programs.
Analysis Separate programs are written
for each component and put to
System
Design work together.

Implementation

Testing

This phase requires the use of a Deployment


programming language like Python.
The implementation involves coding,
Maintenance
testing, and debugging.

88
Testing
Requirement
Testing ensures that the code meets
Specification the requirements specification and
weeds out bugs.
System
Analysis

System
Design

Implementation

Testing
An independent team of software
engineers not involved in the
Deployment
design and implementation of the
project usually conducts such
testing. Maintenance

89
Deployment
Requirement
Specification
Deployment makes the project
available for use.
System
Analysis

System
Design

Implementation

Testing

Deployment

Maintenance

90
Maintenance
Requirement
Specification Maintenance is concerned with
changing and improving the product.
System
Analysis

System
Design

Implementation

Testing
A software product must continue to
perform and improve in a changing
environment. This requires periodic Deployment
upgrades of the product to fix newly
discovered bugs and incorporate Maintenance
changes.
91
Problem: Computing Loan Payments
This program lets the user enter the interest rate,
number of years, and loan amount, and computes
monthly payment and total payment.

loanAmount  monthlyInterestRate
monthlyPayment 
1 1
(1  monthlyInterestRate) numberOfYears12

totalPayment = monthlyPayment * numberOfYears * 12


92
Program 2.13 Computing Loan Payments

93
Program 2.13 Computing Loan Payments

 Output

Enter annual interest rate, e.g., 7.25: 5.75

Enter number of years as an integer, e.g., 5: 15

Enter loan amount, e.g., 120000.95: 250000

The monthly payment is 2076.02

The total payment is 373684.53

94
Case Study: Computing Distances

Program that prompts the user to enter two points,


computes their distance, and displays the points.

95
Program 2.14 Computing Distances

96
Program 2.14 Computing Distances

 Output

Enter x1 and y1 for Point 1: 1.5, -3.4

Enter x2 and y2 for Point 2: 4,5

The distance between the two points is


8.764131445842194

97
Case Study: Computing Distances

This program prompts the user to enter two points,


computes their distance, and displays the points and
their distances in graphics.

98
Program 2.15 Computing Distances in Graphics

import turtle

# Prompt the user for inputing two points

x1, y1 = eval(input("Enter x1 and y1 for Point 1: "))

x2, y2 = eval(input("Enter x2 and y2 for Point 2: "))

# Compute the distance

distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5

99
Program 2.15 Computing Distances in Graphics

# Display two points and the connecting line

turtle.penup()

turtle.goto(x1, y1) # Move to (x1, y1)

turtle.pendown()

turtle.write("Point 1")

turtle.goto(x2, y2) # draw a line to (x2, y2)

turtle.write("Point 2")

100
Program 2.15 Computing Distances in Graphics

# Move to the center point of the line

turtle.penup()

turtle.goto((x1 + x2) / 2, (y1 + y2) / 2)

turtle.write(distance)

turtle.done()

101
Program 2.15 Computing Distances in Graphics

Output:
Enter x1 and y1 for Point 1: 10,100
Enter x2 and y2 for Point 2: 50,200

102
103
104

You might also like