Chapter 02 Elementary Programming
Chapter 02 Elementary Programming
Elementary Programming
1
Motivations
In the preceding chapter, you learned how to create, and run a Python
program.
Starting from this chapter, you will learn how to solve practical problems
programmatically.
Through these problems, you will learn fundamental programming
techniques, such as the use of variables, operators, expressions, and
input and output.
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 will learn the basic steps that go into analyzing a
problem, designing a solution, and implementing the solution by creating
a program.
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 elements such as variables and functions (§2.4).
To assign data to variables (§2.5).
To perform simultaneous assignment (§2.6).
To define named constants (§2.7).
To use the operators +, -, *, /, //, %, and ** (§2.8).
To write and evaluate numeric expressions (§2.9).
To use augmented assignment operators to simplify coding (§2.10).
To perform numeric type conversion and rounding with the int and round functions (§2.11).
To obtain the current system time by using time.time() (§2.12).
To describe the software development process and apply it to develop a loan payment program
(§2.13).
To compute and display the distance between two points in graphics (§2.14).
3
Introducing Programming with an Example
• Writing a program involves designing a strategy for solving
the problem and then using a programming language to
implement that strategy.
• Writing a program involves designing algorithms and then
translating them into programming instructions, or code.
• Listing 2.1 Computing the Area of a Circle
• This program computes the area of the circle.
4
Algorithm ..
• The algorithm for calculating the area of a circle can be
described as follows:
• 1. Get the circle’s radius from the user.
• 2. Compute the area by applying the following formula:
5
Listing 2.1 ComputeArea.py
6
ComputeArea.py …
• If you have programmed in other languages, such as Java,
you know you have to declare a variable with a data type to
specify what type of values are being used, such as integers
or text characters.
• You don’t do this in Python, however, because Python
automatically figures out the data type according to the
value assigned to the variable.
• The statement in line 8 displays four items on the console.
You can display any number of items in a print statement
using the following syntax:
• print(item1, item2, ..., itemk)
7
Reading Input from the Console
Reading input from the console enables the program to accept input
from the user.
In Listing 2.1, a radius is set in the source code. To use a different
radius, you have to modify the source code.
You can use the input function to ask the user to input a value for
the radius.
The following statement prompts the user to enter a value, and then
it assigns the value to the variable:
variable = input("Enter a value: ")
The value entered is a string. 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. 8
LISTING 2.2 ComputeAreaWithConsoleInput.py
1 # Prompt the user to enter a radius
2 radius = eval(input("Enter a value for radius: "))
3
4 # Compute area
5 area = radius * radius * 3.14159
6
7 # Display results
8 print("The area for the circle of radius", radius, "is", area)
9
Explanation …
• Line 2 prompts the user to enter a value (in the form of a
string) and converts it to a number, which is equivalent to
• s = input("Enter a value for radius: ") # Read input as a string
• radius = eval(s) # Convert the string to a number
• After the user enters a number and presses the Enter key,
the number is read and assigned to radius.
10
Multiple inputs
• Listing 2.2 shows how to prompt the user for a single input.
However, you can prompt for multiple inputs as well.
• Listing 2.3 gives an example of reading multiple inputs from
the keyboard.
• This program reads three integers and displays their average.
11
LISTING 2.3 ComputeAverage.py
1 # Prompt the user to enter three numbers
2 number1 = eval(input("Enter the first number: "))
3 number2 = eval(input("Enter the second number: "))
4 number3 = eval(input("Enter the third number: "))
5
6 # Compute average
7 average = (number1 + number2 + number3) / 3
8
9 # Display result
10 print("The average of", number1, number2, number3,
11 "is", average)
12
Identifiers
• Identifiers are the names that identify the elements such as
variables and functions in a program.
An identifier is a sequence of characters that consist of letters,
digits, and underscores (_).
An identifier must start with a letter, or an underscore. It cannot
start with a digit.
An identifier cannot be a reserved word or keyword. (See
Appendix A, “Python Keywords,” for a list of reserved words).
For example, import is a keyword, which tells the Python
interpreter to import a module to the program.
An identifier can be of any length.
13
Quiz
• Which of the following identifiers are valid? Which are
Python keywords?
• miles, Test, a+b, b–a, 4#R, $4, #44, apps, if, elif, x, y, radius
14
Variables, Assignment Statements, and
Expressions
• Variables are used to reference values that may be changed
in the program.
• Variables are the names that reference values stored in
memory.
• They are called “variables” because they may reference
different values.
• For example, in the following code, radius is initially 1.0 (line
2) and then changed to 2.0 (line 7), and area is set to
3.14159 (line 3) and then reset to 12.56636 (line 8).
15
Variables …
1. # Compute the first area
2. radius = 1.0
3. area = radius * radius * 3.14159
4. print("The area is“, area, "for radius“, radius)
5.
6. # Compute the second area
7. radius = 2.0
8. area = radius * radius * 3.14159
9. print("The area is“, area, "for radius “, radius)
16
Assignment Statements
• 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
• An expression represents a computation involving values,
variables, and operators that, taken together, evaluate to a
value.
• For example, consider the following code:
17
Assignment …
•x=1 # Assign 1 to x
• radius = 1.0 # Assign 1.0 to radius
• x = 5 * (3 / 2) + 3 * 2 # Assign the value of the expression to x
•x=y+1 # Assign the addition of y and 1 to x
• area = radius * radius * 3.14159 # Compute area
• You can use a variable in an expression. A variable can also
be used in both sides of the = operator. For example,
• x = x + 1 , same as x += 1
18
Scope of Variables
• Every variable has a scope.
• The scope of a variable is the part of the program where the
variable can be referenced.
• The rules that define the scope of a variable will be
introduced gradually later.
• For now, all you need to know is that a variable must be
created before it can be used. For example, the following
code is wrong:
19
Scope …
20
Assignment …
• 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 interestRate is assigned a value
0.05, but interestrate is not defined.
• Python is case-sensitive. interestRate and interestrate are
two different variables.
21
Simultaneous Assignments
• Python also supports simultaneous assignment in syntax like
this:
• var1, var2, ..., varn = exp1, exp2, ..., expn
• It tells Python to evaluate all the expressions on the right
and assign them to the corresponding variable on the left
simultaneously.
• Swapping variable values is a common operation in
programming and simultaneous assignment is very useful to
perform this operation.
22
Swapping values of two variables
23
LISTING 2.4 ComputeAverageWithSimultaneousAssignment.py
1 # Prompt the user to enter three numbers
2 number1, number2, number3 = eval(input(
3 "Enter three numbers separated by commas: "))
4
5 # Compute average
6 average = (number1 + number2 + number3) / 3
7
8 # Display result
9 print("The average of", number1, number2, number3,
10 "is", average)
24
Named Constants
• A named constant is an identifier that represents a permanent value.
• 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. However, to distinguish a
constant from a variable, use all uppercase letters to name a constant.
• E.g.
PI = 3.14159;
SIZE = 3;
LENGTH = 50;
GENDER = ‘F’;
25
Benefits of using constants
1. You don’t have to repeatedly type the same value if it is
used multiple times.
2. If you have to change the constant’s value (e.g., from 3.14
to 3.14159 for PI), you need to change it only in a single
location in the source code.
3. Descriptive names make the program easy to read.
26
Naming Conventions
Choose short, meaningful and descriptive names.
Variables and function names:
• Use lowercase. If the name consists of several words, concatenate
all in one, use lowercase for the first word, and capitalize the first
letter of each subsequent word in the name. For example, the
variables radius and area, and the method computeArea.
Constants:
• Capitalize all letters in constants, and use underscores to
connect words. For example, the constant PI, SIZE and
MAX_VALUE
27
Numerical Data Types and Operators
• Python has two numeric types—integers and floating-point
numbers—for working with the operators +, -, *, /, //, **,
and %.
• 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.
• 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.
28
Numeric Operators
29
The /, //, and ** Operators
30
** operator
31
The % Operator
• The % operator, known as remainder or modulo operator,
yields the remainder after division.
• The left-side operand is the dividend and the right-side
operand is the divisor.
• Therefore, 7 % 3 yields 1, 3 % 7 yields 3, 12 % 4 yields 0, 26 %
8 yields 2, and 20 % 13 yields 7.
32
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
33
Problem: Displaying Time
• Write a program that obtains hours, minutes and remaining
seconds from seconds.
LISTING 2.5 DisplayTime.py
1 # Prompt the user for input
2 seconds = eval(input("Enter an integer for seconds: "))
3 #get the number of hours
4 hours = seconds // 3600
5 # Get minutes
6remainingSecs = seconds % 3600
7 minutes = remainingSeconds // 60 # Find minutes in seconds
8# Get remaining seconds
9 remainingSeconds = seconds % 60 # Seconds remaining
10 print(seconds, "seconds is", hours, “hours", minutes,
11 "minutes and", remainingSeconds, "seconds")
34
Output
Line 2 reads an integer for seconds. Line 5 obtains the minutes using
seconds // 60. Line 6 (seconds % 60) obtains the remaining seconds
after taking away the minutes.
35
Scientific Notation
36
Note
• The float type is used to represent numbers with a decimal
point. Why are they called floating-point numbers? These
numbers are stored in scientific notation in memory.
• When a number such as 50.534 is converted into scientific
notation, such as 5.0534E+1, its decimal point is moved
(floated) to a new position.
37
Caution
• When a variable is assigned a value that is too large (in size)
to be stored in memory, it causes overflow. For example,
executing the following statement causes overflow.
39
Arithmetic Expressions
Python expressions are evaluated in the same way as
arithmetic expressions.
40
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
41
Order of evaluation – operator precedence
• Parentheses () first
• Exponentiation (**) is applied first.
• Multiplication (*), float division (/), integer division (//) , and
remainder operators (%) are applied next. If an expression
contains several multiplication, division, and remainder
operators, they are applied from left to right.
• Addition (+) and subtraction (-) operators are applied last. If an
expression contains several addition and subtraction operators,
they are applied from left to right.
• BOMDMAS
42
Augmented Assignment Operators
43
Quiz
• Assume that a = 1, and that each expression is independent.
What are the results of the following expressions?
a += 4
a -= 4
a *= 4
a /= 4
a //= 4
a %= 4
a **= 4
a = 56 * a + 6
44
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to Celsius
using the formula:
celsius ( 95 )( fahrenheit 32)
45
Type Conversions and Rounding
• If one of the operands for the numeric operators is a float
value, the result will be a float value.
• Can you perform binary operations with two operands of
different types? Yes.
• If an integer and a float are involved in a binary operation,
Python automatically converts the integer to a float value.
• This is called type conversion.
• So, 3 * 4.5 is the same as 3.0 * 4.5.
46
Type conversion …
• Sometimes, it is desirable to obtain the integer part of a
fractional number.
• You can use the int(value) function to return the integer part
of a float value. For example,
47
Conversion …
• You can also use the round function to round a number to
the nearest whole value. For example,
48
Note …
• The functions int and round do not change the variable
being converted. For example, value is not changed after
invoking the function in the following code:
49
Note ..
• The int function can also be used to convert an integer string into an
integer. For example, int("34") returns 34.
• So you can use the eval or int function to convert a string into an
integer. Which one is better?
• The int function performs a simple conversion. It does not work for a
non-integer string. For example, int("3.4") will cause an error.
• The eval function does more than a simple conversion. It can be used
to evaluate an expression. For example, eval("3 + 4") returns 7.
• However, there is a subtle “gotcha” for using the eval function. The
eval function will produce an error for a numeric string that contains
leading zeros.
• In contrast, the int function works fine for this case. For example,
eval("003") causes an error, but int("003") returns 3.
50
Problem: Keeping Two Digits After Decimal
Points
Write a program that displays the sales tax with two digits
after the decimal point.
LISTING 2.6 SalesTax.py
1 # Prompt the user for input
2 purchaseAmount = eval(input("Enter purchase amount: "))
3
4 # Compute sales tax
5 tax = purchaseAmount * 0.06
6
7 # Display tax amount with two digits after decimal point
8 print("Sales tax is", int(tax * 100) / 100.0)
51
Sample run
52
Run …
• The value of the variable purchaseAmount is 197.55 (line 2).
• The sales tax is 6% of the purchase, so the tax is evaluated as
11.853 (line 5). Note that
tax * 100 is 1185.3
int(tax * 100) is 1185
int(tax * 100) / 100.0 is 11.85
• So, the statement in line 8 displays the tax 11.85 with two
digits after the decimal point.
53
Problem: Displaying Current Time
Write a program that displays current time in GMT in the format
hour:minute:second such as 13:19:18.
The time() function in the time module returns the current time seconds
with millisecond precision elapsed since the time 00:00:00 on January 1,
1970 GMT, as shown in Figure 2.1. This time is known as the UNIX
epoch. The epoch is the point when time starts. 1970 was the year when
the UNIX operating system was formally introduced.
Elapsed
time
Time
Unix Epoch Current Time
01-01-1970 time.time()
00:00:00 GMT
54
Current time …
55
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 using integer division (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
using integer division (20053051 minutes // 60 = 334217 hours).
7. Compute the current hour from totalHours % 24 (334217 hours %
24 = 17, which is the current hour).
56
LISTING 2.7 ShowCurrentTime.py
1 import time
2
3 currentTime = time.time() # Get current time
4
5 # Obtain the total seconds since midnight, Jan 1, 1970
6 totalSeconds = int(currentTime)
7
8 # Get the current second
9 currentSecond = totalSeconds % 60
10
11 # Obtain the total minutes
12 totalMinutes = totalSeconds // 60
57
13
14 # Compute the current minute in the hour
15 currentMinute = totalMinutes % 60
16
17 # Obtain the total hours
18 totalHours = totalMinutes // 60
19
20 # Compute the current hour
21 currentHour = totalHours % 24
22
23 # Display results
24 print("Current time is", currentHour, ":",
25 currentMinute, ":", currentSecond, "GMT")
58
59
Software Development Process
60
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
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.
62
System Design
Requirement
Specification
The process of designing the
system’s components.
System
Analysis
System
Design
Implementation
Testing
System
Analysis Input, Process, Output
System
Design
Implementation
Testing
64
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 Java or Deployment
Python. The implementation
involves coding, testing, and Maintenance
debugging.
65
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
66
Deployment
Requirement
Specification Deployment makes the project
available for use.
System
Analysis
System
Design
Implementation
Testing
67
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.
68
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 ) numberOfYears12
69
LISTING 2.8 ComputeLoan.py
1 # Enter annual interest rate as a percentage, e.g., 7.25
2 annualInterestRate = eval(input(
3 "Enter annual interest rate, e.g., 7.25: "))
4 monthlyInterestRate = annualInterestRate / 1200
5
6 # Enter number of years
7 numberOfYears = eval(input(
8 "Enter number of years as an integer, e.g., 5: "))
9
10 # Enter loan amount
70
ComputeLoan.py …
11 loanAmount = eval(input("Enter loan amount, e.g., 120000.95: "))
12
13 # Calculate payment
14 monthlyPayment = loanAmount * monthlyInterestRate / (1
15 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
16 totalPayment = monthlyPayment * numberOfYears * 12
17
18 # Display results
19 print("The monthly payment is", int(monthlyPayment * 100) / 100)
20 print("The total payment is", int(totalPayment * 100) /100)
71
Case Study: Computing Distances
• Given two points, the formula for computing the distance is
73
LISTING 2.10 ComputeDistanceGraphics.py
• This program
1.Prompts the user to enter two points.
2.Computes the distance between the points.
3.Uses Turtle graphics to display the line that connects the
two points.
4.Displays the length of the line at the center of the line.
74
1 import turtle
2
3 # Prompt the user for inputting two points
4 x1, y1 = eval(input("Enter x1 and y1 for point 1: "))
5 x2, y2 = eval(input("Enter x2 and y2 for point 2: "))
6
7 # Compute the distance
8 distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
9
10 # Display two points and the connecting line
11 turtle.penup()
75
12 turtle.goto(x1, y1) # Move to (x1, y1)
13 turtle.pendown()
14 turtle.write("Point 1")
15 turtle.goto(x2, y2) # Draw a line to (x2, y2)
16 turtle.write("Point 2")
17
18 # Move to the center point of the line
19 turtle.penup()
20 turtle.goto((x1 + x2) / 2, (y1 + y2) / 2)
21 turtle.write(distance)
22
23 turtle.done()
76
Program summary
• The program prompts the user to enter the value for two
points (x1, y1) and (x2, y2), and computes their distance
(lines 4–8).
• It then moves to (x1, y1) (line 12), displays the text Point 1
(line 14), draws a line from (x1, y1) to (x2, y2) (line 15), and
displays the text Point 2 (line 16).
• Finally, it moves to the center of the line (line 20) and
displays the distance (line 21).
77
Q&A????
78