[go: up one dir, main page]

0% found this document useful (0 votes)
8 views54 pages

02 Slide

Chapter 2 of the document introduces elementary programming concepts, focusing on writing programs for simple computations, such as calculating loan payments and the area of a circle. It covers essential programming topics including variable naming, assignment, data types, operators, and the software development process. The chapter emphasizes the importance of understanding problem analysis, designing solutions, and implementing them through programming.

Uploaded by

daviesikeoluwa7
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)
8 views54 pages

02 Slide

Chapter 2 of the document introduces elementary programming concepts, focusing on writing programs for simple computations, such as calculating loan payments and the area of a circle. It covers essential programming topics including variable naming, assignment, data types, operators, and the software development process. The chapter emphasizes the importance of understanding problem analysis, designing solutions, and implementing them through programming.

Uploaded by

daviesikeoluwa7
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/ 54

Chapter 2 Elementary Programming

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


1
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.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


2
Objectives
To write programs that perform simple computations (§2.2).
To obtain input from a program’s user by using the input function
(§2.3).
To use identifiers to name variables (§2.4).
To assign data to variables (§2.5).
To define named constants (§2.6).
To use the operators +, -, *, /, //, %, and ** (§2.7).
To write and evaluate numeric expressions (§2.8).
To use augmented assignment operators to simplify coding (§2.9).
To perform numeric type conversion and rounding with the int and
round functions (§2.10).
To obtain the current system time by using time.time() (§2.11).
To describe the software development process and apply it to
develop the loan payment program (§2.12).
To compute and display the distance between two points (§2.13).

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


3
Introducing Programming with an
Example
Listing 2.1 Computing the Area of a
Circle
This program computes the area of the
circle. IMPORTANT NOTE:
(1) To enable the buttons, you must download the entire slide
file slide.zip and unzip the files into a directory (e.g.,
ComputeArea c:\slide). (2) You must have installed Python and set python
bin directory in the environment path. (3) If you are using
Office 2010, check PowerPoint2010.doc located in the
Run same folder with this ppt file.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
4
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))

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


5
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)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


6
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)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


7
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.

ComputeAreaWithConsoleInput ComputeAverage
Run Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
8
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


10
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


Variables
# 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)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


14
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


15
Assignment Statements
• We assign a value to a variable using the
assignment statement (=)
• An assignment statement consists of an
expression on the right hand side and a
variable to store the result

x = 3.9 * x * ( 1 - x )

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

Right side is an expression. Once 0.93


expression is evaluated, the result
is placed in (assigned to) x.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


A variable is a memory location
used to store a value. The value
stored in a variable can be updated x 0.6 0.93
by replacing the old value (0.6)
with a new value (0.93).

x = 3.9 * x * ( 1 - x )

Right side is an expression. Once


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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


Assignment Statements
x = 1 # Assign 1 to x

x = x + 1
i = j = k = 1

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


19
Simultaneous Assignment

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

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

ComputeAverageWithSimultaneousAssignment

Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
20
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.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


21
Numerical Data Types

integer: e.g., 3, 4
float: e.g., 3.0, 4.0

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


22
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, < class 'float'>
98.6, 14.0 >>> type(1)
< class 'int'>
• There are other number >>> type(1.0)
types - they are variations < class 'float'>
>>>
on float and integer

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


24
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


25
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


26
Problem: Displaying Time
Write a program that obtains hours and
minutes from seconds.

DisplayTime Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


27
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'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


28
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.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


29
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.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


30
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)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


31
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


Operator Precedence Rules
• Highest precedence rule to
lowest precedence rule
• Parenthesis are always
respected
• Exponentiation (raise to a
power) Parenthesis
Power
• Multiplication, Division, and Multiplication
Addition
Remainder Left to Right
• Addition and Subtraction
• Left to right

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


>>> 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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


>>> 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.
Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


Operator Precedence
• Remember the rules top to bottom Parenthesis
• When writing code - use Power
Multiplication
parenthesis Addition
• When writing code - keep Left to Right

mathematical expressions simple


enough that they are easy to
understand
• Break long series of mathematical
operations up to make them more
clear
Exam Question: x = 1 + 2 * 3 - 4 / 5

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
37
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
>>> print (1 + 2 * 3 / 4.0 – 5)
floating point
-2.5
• The integer is >>>
converted to a
floating point before
the operation

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


39
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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


40
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.

SalesTax Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


41
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 ShowCurrentTime
Time
Unix epoch Current time
01-01-1970
00:00:00 GMT
time.time() Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
42
Software Development Process
Requirement
Specification

System
Analysis

System
Design

Implementation

Testing

Deployment

Maintenance

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

Implementation

Testing

Most of the examples in this book are simple,


and their requirements are clearly stated. In Deployment

the real world, however, problems are not


well defined. You need to study a problem Maintenance
carefully to identify its requirements.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
44
System Analysis
Requirement
Specification Seeks to analyze the business
process in terms of data flow, and
System
Analysis to identify the system’s input and
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.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
45
System Design
Requirement
Specification
The process of designing the
system’s components.
System
Analysis

System
Design

Implementation

Testing

This phase involves the use of many levels


Deployment
of abstraction to decompose the problem into
manageable components, identify classes and
interfaces, and establish relationships among Maintenance
the classes and interfaces.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
46
IPO
Requirement
Specification

System
Analysis Input, Process, Output

System
Design

Implementation

Testing

The essence of system analysis and design is input,


process, and output. This is called IPO. Deployment

Maintenance

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

Implementation

Testing
This phase requires the use of a
programming language like Python. Deployment
The implementation involves
coding, testing, and debugging. Maintenance

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


48
Testing
Requirement
Specification Ensures that the code meets the
requirements specification and
System
Analysis weeds out bugs.
System
Design

Implementation

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

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

System
Design

Implementation

Testing

Deployment

Maintenance

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


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

Implementation

Testing
A software product must continue to
perform and improve in a changing Deployment
environment. This requires periodic
upgrades of the product to fix newly Maintenance
discovered bugs and incorporate changes.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
51
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

ComputeLoan Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
52
Case Study: Computing Distances

This program prompts the user to enter two


points, computes their distance, and displays
the points.

ComputeDistance Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
53
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.

ComputeDistanceGraphics Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
54

You might also like