CPIT110 - Chapter 2
CPIT110 - Chapter 2
CPIT110 - Chapter 2
Elementary Programming
CPIT 110 (Problem-Solving and Programming)
Version 1.2
Sections
• 2.1. Motivations
• 2.2. Writing a Simple Program
• 2.3. Reading Input from the Console
• 2.4. Identifiers
• 2.5. Variables, Assignment Statements, and Expressions
• 2.6. Simultaneous Assignments
• 2.7. Named Constants
• 2.8. Numeric Data Types and Operators
• 2.9. Evaluating Expressions and Operator Precedence
• 2.10. Augmented Assignment Operators
• 2.11. Type Conversions and Rounding
• 2.12. Case Study: Displaying the Current Time
• 2.13. Software Development Process
• 2.14. Case Study: Computing Distances
Programs Check Points 2
Programs
• Program 1: Compute Area
• Program 2: Compute Area With Console Input
• Program 3: Compute Average
• Program 4: Compute Average With Simultaneous Assignment
• Program 5: Compute Area with a Constant
• Program 6: Convert Time
• Problem 7: Keeping Two Digits After Decimal Points
• Problem 8: Displaying Current Time
• Problem 9: Computing Loan Payments
3
Check Points
• Section 2.2 ◦ #7
◦ #1 • Section 2.9
◦ #2 ◦ #8
• Section 2.3 ◦ #9
◦ #3 • Section 2.10
• Section 2.4 ◦ #10
◦ #4 • Section 2.11
• Section 2.6 ◦ #11
◦ #5 ◦ #12
• Section 2.8
◦ #6
4
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 (2.14).
5
Get Ready
6
Get Ready
• In this chapter, you will learn many basic concepts in Python programming. So,
You may need to try some codes in a quick way.
• You learned in the previous chapter that Python has two modes: interactive mode
and script mode.
• In the interactive mode, you don’t have to create a file to execute the code. Also,
you don’t have to use the print function to display results of expressions and
values of variables.
• Python provides Python Shell for programming in the interactive mode.
• You can use Python Shell in form of command line using (“Python 3.7”) or GUI
(Graphical User Interface) using (“IDLE”).
Get Ready 7
Python Shell (Command Line)
Get Ready 8
Python Shell (GUI)
Get Ready 9
Python Shell in PyCharm
• Open or create a project in PyCharm.
Get Ready 10
2.1. Motivations
11
Motivations
• In the preceding chapter (Chapter 1), 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 Python basic data types and
related subjects, such as variables, constants, data types, operators,
expressions, and input and output.
2.1 12
2.2. Writing a Simple Program
▪ Program 1: Compute Area
▪ Data Types
▪ Python Data Types
▪ Check Point #1 - #2
13
Compute Area
Program 1
Write a program that will calculate the area of a circle.
area = radius x radius x π
Here is a sample run of the program (suppose that radius is 20):
The area for the circle of radius 20 is 1256.636
• Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
2.2 Program 1 14
Compute Area
Phase 1: Problem-solving
Write a program that will calculate the area of a circle.
• Phase 1: Design your algorithm
1. Get the radius of the circle.
2. Compute the area using the following formula:
area = radius x radius x π
3. Display the result
▪ Tip:
It’s always good practice to outline your program (or its underlying
problem) in the form of an algorithm (Phase 1) before you begin
coding (Phase 2).
2.2 Program 1 15
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
ComputeArea.py
2.2 Program 1 16
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
◦ In this problem, the program needs to read the radius, which the
program’s user enters from the keyboard.
◦ This raises two important issues:
▪ Reading the radius from the user. → Solution: using the input function
▪ Storing the radius in the program. → Solution: using variables
◦ Let’s address the second issue first.
2.2 Program 1 17
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
◦ In order to store the radius, the program must create a symbol
called a variable.
◦ A variable is a name that references a value stored in the
computer’s memory.
◦ You should choose descriptive names for variables
▪ Do not choose “x” or “y”… these have no meaning
▪ Choose names with meaning …“area” or “radius”
2.2 Program 1 18
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
◦ The first step is to create and set a value for radius.
▪ Later we will learn how to ask the user to input the value for radius!
▪ For now, you can assign a fixed value to radius in the program as you write the
code. For example, let radius be 20
ComputeArea.py
1 # Step 1: Assign a value to radius
2 radius = 20 # radius is now 20
3
4 # Step 2: Compute area
5
6
7 # Step 3: Display results
8
2.2 Program 1 19
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
◦ The second step is to compute area by assigning the result of the
expression (radius * radius * 3.14159) to area.
▪ Note that: π = 3.14159, so we can rewrite the equation (area = radius x radius x π) to
be (area = radius x radius x 3.14159).
ComputeArea.py
1 # Step 1: Assign a value to radius
2 radius = 20 # radius is now 20
3
4 # Step 2: Compute area
5 area = radius * radius * 3.14159
6
7 # Step 3: Display results
8
2.2 Program 1 20
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
◦ The final step is to display the value of area on the console by using
Python’s print function.
ComputeArea.py
1 # Step 1: Assign a value to radius
2 radius = 20 # radius is now 20
3
4 # Step 2: Compute area
5 area = radius * radius * 3.14159
6
7 # Step 3: Display results
8 print("The area for the circle of radius ", radius, " is ", area)
2.2 Program 1 21
Compute Area
Phase 2: Implementation
Write a program that will calculate the area of a circle.
• Phase 2: Implementation (code the algorithm)
LISTING 2.1 ComputeArea.py
1 # Assign a value to radius
2 radius = 20 # radius is now 20
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)
2.2 Program 1 22
Compute Area
Trace The Program Execution
It is a comment. Do Nothing.
2.2 1 of 6 Program 1 23
Compute Area
Trace The Program Execution
Assign 20 to radius
2.2 2 of 6 Program 1 24
Compute Area
Trace The Program Execution
It is a comment. Do Nothing.
2.2 3 of 6 Program 1 25
Compute Area
Trace The Program Execution
Assign the result (1256.636) to area
2.2 4 of 6 Program 1 26
Compute Area
Trace The Program Execution
It is a comment. Do Nothing.
2.2 5 of 6 Program 1 27
Compute Area
Trace The Program Execution
Print the message to the console.
2.2 6 of 6 Program 1 28
Compute Area
LISTING 2.1 ComputeArea.py Discussion
1 # Assign a radius
2 radius = 20 # radius is now 20
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)
2.2 Program 1 30
Compute Area
LISTING 2.1 ComputeArea.py Discussion
1 # Assign a radius
2 radius = 20 # radius is now 20
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)
• The following table shows the value in memory for the variables
area and radius as the program is executed.
Line # radius area
2 20 It does not exist
5 1256.636
2.2 Program 1 31
Compute Area
LISTING 2.1 ComputeArea.py Discussion
1 # Assign a radius
2 radius = 20 # radius is now 20
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)
• You can display any number of items in a print statement using the
following syntax:
print(item1, item2 , ..., itemk)
• If an item is a number, the number is automatically converted to a
string for displaying.
2.2 Program 1 32
Data Types
• A variable represents a value stored in the computer’s memory.
• Every variable has a name and value.
• Every value has a data type, and the data type is to specify what
type of the value are being used, such as integers or strings (text
characters).
• In many programming languages such as Java, you have to define
the type of the variable before you can use it. You don’t do this in
Python.
• However, Python automatically figures out the data type of a
variable according to the value assigned to the variable.
2.2 33
Python Data Types
• Python provides basic (built-in) data types for integers, real
numbers, string, and Boolean types.
• Here are some examples of different types of values stored in
different variables:
var1 = 25 # Integer
var2 = 25.8 # Float
var3 = "Ahmad" # String
var4 = 'Python' # String
var5 = True # Boolean
2.2 34
Check Point
#1
Show the printout of the following code:
1 width = 5.5
2 height = 2
3 print("area is", width * height)
➢ Solution: area is 11
2.2 35
Check Point
#2
Translate the following algorithm into Python code:
◦ Step 1: Use a variable named miles with initial value 100.
◦ Step 2: Multiply miles by 1.609 and assign it to a variable named kilometers.
◦ Step 3: Display the value of kilometers.
➢ Solution:
1 miles = 100
2 kilometers = miles * 1.609
3 print("kilometers = ", kilometers)
◦ kilometers after Step 3 is 160.9
2.2 36
2.3. Reading Input from the Console
▪ input(…)
▪ eval(…)
▪ Program 2: Compute Area With Console Input
▪ Program 3: Compute Average
▪ Line Continuation Symbol (\)
▪ IPO
▪ Check Point #3
37
input(…)
• In the last example, the radius was fixed.
• To use a different radius, you have to modify the source code.
• Your program can be better, and more interactive, by letting the user
enter the radius.
• Python uses the input function for console input.
• The input function is used to ask the user to input a value, and then
return the value entered as a string (string data type).
• The following statement prompts (asks) the user to enter a value,
and then it assigns the value to the variable:
variable = input("Enter a value: ")
2.3 38
input(…)
• The example of the output of the previous statement is shown in the
following figure (Python Shell – Interactive mode).
Remember that the Python Shell shows the result of the executed
expression automatically even you didn't use the print function.
2.3 39
input(…)
• Does it matter if a numeric value is being stored as a string, not a
number?
• Yes, it does. See the following examples:
2.3 40
eval(…)
• You can use eval function to evaluate and convert the passed value
(string) to a numeric value.
1 eval("34.5") # returns 34.5 (float)
2 eval("345") # returns 345 (integer)
3 eval("3 + 4") # returns 7 (integer)
4 eval("51 + (54 * (3 + 2))") # returns 321 (integer)
• So, to get an input (value) from the user as a number and store it
into the variable x, you can write the following code:
x = eval(input("Enter the value of x: "))
• Also, you can separate the process into two lines if you would like:
x = input("Enter the value of x: ") # Read x as string
x = eval(x) # Convert value x to number and save it to x
2.3 41
Compute Area With Console Input
Program 2
• Now, let us revisit the last example (Program 1), and modify it in
order to let the user enter the radius value.
LISTING 2.2 ComputeAreaWithConsoleInput.py
2.3 Program 2 42
Compute Area With Console Input
Discussion
LISTING 2.2 ComputeAreaWithConsoleInput.py
• 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:
# Read input as a string
radius = input("Enter a value for radius: ")
# Convert the string to a number
radius = eval(radius)
• After the user enters a number and presses the <Enter> key, the
number is read and assigned to radius.
2.3 Program 2 43
Compute Average
Program 3
Write a program to get three values from the user and compute
their average.
Enter the first number: 1 <Enter>
Enter the second number: 2 <Enter>
Enter the third number: 3 <Enter>
The average of 1 2 3 is 2.0
• Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
2.3 Program 3 44
Compute Average
Phase 1: Problem-solving
Write a program to get three values from the user and compute
their average.
• Phase 1: Design your algorithm
1. Get three numbers from the user.
▪ Use the input function.
2. Compute the average of the three numbers:
average = (num1 + num2 + num3) / 3
3. Display the result
2.3 Program 3 45
Compute Average
Phase 2: Implementation
Write a program to get three values from the user and compute
their average.
• Phase 2: Implementation (code the algorithm)
# Compute average
# Display result
2.3 Program 3 46
Compute Average
Phase 2: Implementation
Write a program to get three values from the user and compute
their average.
• Phase 2: Implementation (code the algorithm)
LISTING 2.3 ComputeAverage.py
2.3 Program 3 47
Compute Average
Example Runs of The Program
Enter the first number: 1 <Enter>
Enter the second number: 2 <Enter>
Enter the third number: 3 <Enter>
The average of 1 2 3 is 2.0
2.3 Program 3 48
Compute Average
LISTING 2.3 ComputeAverage.py Discussion
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)
• The program prompts the user to enter three integers (lines 2–4),
computes their average (line 7), and displays the result (lines 10–
11).
• If the user enters something other than a number, the program will
terminate with a runtime error.
2.3 Program 3 49
Compute Average
LISTING 2.3 ComputeAverage.py Discussion
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)
2.3 Program 3 50
Line Continuation Symbol (\)
• In some cases, the Python interpreter cannot determine the end of
the statement written in multiple lines. You can place the line
continuation symbol (\) at the end of a line to tell the interpreter
that the statement is continued on the next line.
• For example, the following statement:
1 sum = 1 + 2 + 3 + 4 + \
2 5 + 6
is equivalent to
1 sum = 1 + 2 + 3 + 4 + 5 + 6
2.3 51
IPO
• Most of the programs in early chapters of this book perform
three steps: Input, Process, and Output, called IPO.
• Input is to receive input from the user.
• Process is to produce results using the input.
• Output is to display the results.
Data Information
Input Process Output
2.3 52
Check Point
#3
What happens if the user enters 5a when executing the following
code?
1 radius = eval(input("Enter a radius: "))
2.3 53
2.4. Identifiers
▪ Python Keywords
▪ Check Point #4
54
Identifiers
• Identifiers are the names that identify the elements such as
variables and functions in a program.
• All identifiers must obey the following rules:
◦ An identifier is a sequence of characters that consists 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 Keyword.
▪ Keywords, also called reserved words, have special meanings in Python.
▪ 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.
2.4 55
Identifiers
• Examples of legal identifiers:
◦ area , radius, ComputeArea, _2, average, If, IN
• Examples of illegal identifiers:
◦ 2A, d+4, a*, test#, @hmad, if, in
▪ These do not follow the rules.
▪ if and in are keywords in Python.
▪ Python will report that you have a syntax error!
2.4 56
Python Keywords
• Keywords are reserved words by programming language.
• Keywords can not be used as identifiers.
• The following is the list of Python keywords:
2.4 57
Check Point
#4
Which of the following identifiers are valid? Which are Python
keywords?
1. miles ✔
2. Test ✔
3. a+b ❌
4. b–a ❌
5. 4#R ❌
6. $4 ❌
7. #44 ❌
8. apps ✔
9. elif ❌ (Keyword)
10. if ❌ (Keyword)
11. y ✔
12. iF ✔
2.4 58
2.5. Variables, Assignment Statements,
and Expressions
▪ Variables
▪ Assignment Statements
▪ Expression
▪ Assigning a Value To Multiple Variables
▪ Scope of Variables
59
Variables
• Variables are used to reference (represent) values that may be
changed in the program.
◦ In the previous programs, we used variables to store values: area,
radius, average.
• They are called variables because their values can be changed!
2.5 60
Variables
• For example, see the following code:
1 # Compute the first area
2 radius = 1.0 radius → 1.0
3 area = radius * radius * 3.14159 area → 3.14159
4 print("The area is", area, "for radius", radius)
5
6 # Compute the second area
7 radius = 2.0 radius → 2.0
8 area = radius * radius * 3.14159 area → 12.56636
9 print("The area is", area, "for radius", radius)
• Discussion:
◦ radius is initially 1.0 (line 2)
then changed to 2.0 (line 7)
◦ area is set to 3.14159 (line 3)
then reset to 12.56636 (line 8)
2.5 61
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 = value
• or
variable = expression
2.5 62
Expression
• An expression represents a computation involving values,
variables, and operators that, taken together, evaluate to a
value.
• For example, consider the following code:
1 y = 1 # Assign 1 to variable y
2 radius = 1.0 # Assign 1.0 to variable radius
3 x = 5 * (3 / 2) + 3 * 2 # Assign the value of the expression to x
4 x = y + 1 # Assign the addition of y and 1 to x
5 area = radius * radius * 3.14159 # Compute area
2.5 63
Expression
• A variable can also be used in both sides of the = operator.
• For example:
x = x + 1
• In this assignment statement, the result of x + 1 is assigned to
x. If x is 1 before the statement is executed, then it becomes 2
after the statement is executed.
• If x is not created before, Python will report an error.
2.5 64
Note
• In mathematics, x = 2 * x + 1 denotes an equation.
• However, in Python, x = 2 * x + 1 is an assignment statement
that evaluates the expression 2 * x + 1 and assigns the
result to x.
2.5 65
Assigning a Value To Multiple Variables
• If a value is assigned to multiple variables, you can use a syntax
like this:
i = j = k = 1
• which is equivalent to
k = 1
j = k
i = j
2.5 66
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 (used).
• A variable must be created before it can be used.
• For example, the following code is wrong:
2.5 67
Scope of Variables
• To fix the previous example, you may write the code like
this:
2.5 68
Caution
• A variable must be assigned a value before it can be used in an
expression.
• For example:
interestRate = 0.05
interest = interestrate * 45
2.5 69
2.6. Simultaneous Assignments
▪ Swapping Variable Values
▪ Obtaining Multiple Input In One Statement
▪ Program 4: Compute Average With Simultaneous
Assignment
▪ Check Point #5
70
Simultaneous Assignment
• 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.
• Example:
x, y, name = 15, 20.5, "Ahmad"
2.6 71
Swapping Variable Values
• 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
2.6 72
Obtaining Multiple Input In One Statement
• Simultaneous assignment can also be used to obtain multiple
input in one statement.
• Program 3 gives an example that prompts the user to enter
three numbers and obtains their average.
• This program can be simplified using a simultaneous
assignment statement, as shown in the following slide
(Program 4).
2.6 73
Program 4: Compute Average With
Simultaneous Assignment
LISTING 2.4 ComputeAverageWithSimultaneousAssignment.py
2.6 Program 4 74
Check Point
#5
Assume that a = 1 and b = 2. What is a and b after the following
statement?
a, b = b, a
➢ Answer:
a=2
b=1
2.6 75
2.7. Named Constants
▪ Program 5: Compute Area with a Constant
▪ Benefits of Using Constants
▪ Naming Conventions
76
Named Constants
• A named constant is an identifier that represents a permanent
value.
• The value of a variable can change during execution of a program.
• However, a named constant, or simply constant, represents a
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.
• Example:
PI = 3.14159 # This is a constant
2.7 77
Compute Area with a Constant
Program 5
• In our Compute Area program (Program 1), π is a constant.
• If you use it frequently, you don’t want to keep typing 3.14159;
instead, you can use a descriptive name PI for the value.
1 # Assign a radius
2 radius = 20 # radius is now 20
3
4 # Compute area
5 PI = 3.14159
6 area = radius * radius * PI
7
8 # Display results
9 print("The area for the circle of radius", radius, "is", area)
2.7 Program 5 78
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 (for example, 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.
2.7 79
Naming Conventions
• Choose meaningful and descriptive names.
◦ Do not use abbreviations.
▪ For example: use average instead of avg.
2.7 80
Naming Conventions
Variables and function names:
◦ Use lowercase.
▪ For example: radius, area.
◦ 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.
▪ This naming style is known as the camelCase.
▪ For example: computeArea, interestRate, yourFirstName.
◦ Or use lowercase for all words and concatenate them using
underscore ( _ ).
▪ For example: compute_area, interest_rate, your_first_name.
2.7 81
Naming Conventions
• Constants:
◦ Capitalize all letters in constants and use underscores to connect
words.
▪ For example: PI, MAX_VALUE.
2.7 82
2.8. Numeric Data Types and Operators
▪ Numeric Data Types
▪ Numeric Operators
▪ Unary Operator & Binary Operator
▪ Float Division ( / ) Operator
▪ Integer Division ( // ) Operator
▪ Exponentiation ( ** ) Operator
▪ Remainder (%) Operator
▪ Program 6: Convert Time
▪ Check Point #6 - #7
83
Numeric Data Types
• The information stored in a computer is generally referred to as
data.
• There are two types of numeric data: integers and real numbers.
• Integer types (int for short) are for representing whole numbers.
• Real types are for representing numbers with a fractional part.
• Inside the computer, these two types of data are stored differently.
• Real numbers are represented as floating-point (or float) values.
2.8 84
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.
• 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.
n1 = 5 # Integer
n2 = 5.0 # Float
n3 = 10 + 20 # Integer -> 30
n4 = 10.0 + 20.0 # Float -> 30.0
n5 = 10.0 + 20 # Float -> 30.0
2.8 85
Numeric Operators
2.8 86
Unary Operator & Binary Operator
• The +, -, and * operators are straightforward, but note that the
+ and - operators can be both unary and binary.
• A unary operator has only one operand; a binary operator has
two.
• For example, the - operator in -5 is a unary operator to negate
the number 5, whereas the – operator in 4 - 5 is a binary
operator for subtracting 5 from 4.
e1 = -10 + 50 # 40
e2 = -10 + -50 # -60
e3 = +10 + +20 # 30
e4 = +10++20 # 30
e5 = 10++20 # 30
e6 = -20--30 # 10
2.8 87
Float Division ( / ) Operator
• The / operator performs a float division that results in a
floating number. For example:
>>> 4 / 2
2.0
>>> 2 / 4
0.5
>>>
2.8 88
Integer Division ( // ) Operator
• The // operator performs an integer division; the result is an
integer, and any fractional part is truncated. For example:
>>> 5 // 2
2
>>> 2 // 4
0
>>>
2.8 89
Exponentiation ( ** ) Operator
• To compute 𝒂𝒃 (a with an exponent of b) for any numbers a
and b, you can write a ** b in Python. For example:
2.8 90
Remainder (%) 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.
• Examples:
7%3=1 3%7 =3 12 % 4 = 0
26 % 8 = 2 20 % 13 = 7
2.8 91
Remainder (%) Operator
• Remainder is very useful in programming.
• For example, an even number % 2 is always 0
• An odd number % 2 is always 1
• So you can use this property to determine whether a number is
even or odd.
• You can also mod by other values to achieve valuable results.
>>> 100 % 2
0
>>> 99 % 2
1
>>>
2.8 92
Remainder (%) Operator
Example
• If today is Friday, it will be Friday again in 7 days. Suppose you and
your friends will meet in 10 days. What day is it in 10 days?
• Let us assume Sunday is the 1st day of the week.
7%7=0
1 2 3 4 5 6 7 (0)
• We can find that in 10 days, the day will be Monday by using the
following equation:
Friday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Monday
After 10 days
2.8 93
Convert Time
Program 6
Write a program to get an amount of time from the user in
seconds. Then your program should convert this time into
minutes and the remaining seconds.
• Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
2.8 Program 6 94
Convert Time
Phase 1: Problem-solving
• If you are given seconds, how do you then calculate the minutes and
remaining seconds?
• Example:
◦ Given 624 seconds, how do we calculate the minutes?
◦ We divide by 60!
▪ We see how many complete 60s are in 624.
▪ Answer: 10 of them. 10 x 60 = 600.
◦ So in 624 seconds, there are a full 10 minutes.
◦ After we remove those 10 minutes, how many seconds are
remaining?
▪ 624 - (10 x 60) = 24 seconds remaining
▪ We can use mod! 624 % 60 = 24 seconds remaining
2.8 Program 6 95
Convert Time
Phase 1: Problem-solving
• Design your algorithm:
1. Get amount of seconds from the user.
▪ Use input function
2. Compute the minutes and seconds remaining:
▪ From these seconds, determine the number of minutes
▪ Example:
▪ 150 seconds => 2 minutes and 30 seconds
• 150 // 60 = 2 and 150 % 60 = 30
▪ 315 seconds => 5 minutes and 15 seconds
• 315 // 60 = 5 and 315 % 60 = 15
3. Display the result
2.8 Program 6 96
Convert Time
Phase 2: Implementation
LISTING 2.5 DisplayTime.py
2.8 Program 6 97
Convert Time
Trace The Program Execution
Enter an integer for seconds: 500 <Enter>
500 seconds is 8 minutes and 20 seconds
2.8 Program 6 98
Note
• Calculations involving floating-point numbers are approximated
because these numbers are not stored with complete accuracy.
• For example:
print(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1)
▪ displays 0.5000000000000001, not 0.5, and:
print(1.0 - 0.9)
▪ displays 0.09999999999999998, not 0.1.
2.8 99
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'
>>>
2.8 100
Underflow
• When a floating-point number is too small (for example, too
close to zero) to be stored, it causes underflow.
• Python approximates it to zero. So normally you should not be
concerned with underflow.
2.8 101
Scientific Notation
• Floating-point literals can also be specified in scientific
notation.
• 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.
>>> 20e2 >>> 123.456e2
2000.0 12345.6
>>> 123.456e3 >>> 123.456e-2
123456.0 1.23456
>>> 20e3 >>>
20000.0
2.8 102
Check Point
#6
What are the results of the following expressions?
Expression Result
42 / 5 8.4
42 // 5 8
42 % 5 2
40 % 5 0
1%2 1
2%1 0
45 + 4 * 4 - 2 59
45 + 43 % 5 * (23 * 3 % 2) 48
5 ** 2 25
5.1 ** 2 26.009999999999998
2.8 103
Check Point
#7
If today is Tuesday, what day of the week will it be in 100 days?
Suppose that Saturday is 1st day in a week.
➢ Answer: Thursday
1 2 3 4 5 6 7 (0)
(4 + 100) % 7 is 6
After 100 days The 6th day in a week is Thursday
2.8 104
2.9. Evaluating Expressions and
Operator Precedence
▪ Arithmetic Expressions
▪ How to Evaluate an Expression
▪ Check Point #8 - #9
105
Arithmetic Expressions
• Python expressions are written the same way as normal
arithmetic expressions.
• Example:
3 + 4𝑥 10 𝑦 − 5 (𝑎 + 𝑏 + 𝑐) 4 9+𝑥
− +9 +
5 𝑥 𝑥 𝑦
• It is translated into:
((3 + (4 * x)) / 5) - ((10 * (y - 5) * (a + b + c)) / x) + (9 * ((4 / x) + ((9 + x) / y)))
Zoom In
2.9 106
Arithmetic Expressions
Explanation
3 + (4 * x) 10 * ( y – 5 ) * ( a + b + c )
3 + 4𝑥 10 𝑦 − 5 (𝑎 + 𝑏 + 𝑐) 4 9+𝑥
− +9 +
5 𝑥 𝑥 𝑦
Expression
3 + (4 ∗ 𝑥) 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) 4 9+𝑥
− +9 +
5 𝑥 𝑥 𝑦
2.9 1 of 4 107
Arithmetic Expressions
Explanation
( ( 3 + (4 * x) ) / 5 ) ( ( 10 * ( y – 5 ) * ( a + b + c ) ) / x )
3 + (4 ∗ 𝑥) 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) 4 9+𝑥
− +9 +
5 𝑥 𝑥 𝑦
Expression
4 9+𝑥
( ( 3 + (4 ∗ 𝑥) ) / 5 ) − ( ( 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) ) / 𝑥 ) + 9 +
𝑥 𝑦
2.9 2 of 4 108
Arithmetic Expressions
Explanation
((9+x)/y)
(4/x)
4 9+𝑥
( ( 3 + (4 ∗ 𝑥) ) / 5 ) − ( ( 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) ) / 𝑥 ) + 9 +
𝑥 𝑦
Expression
( ( 3 + (4 ∗ 𝑥) ) / 5 ) − ( ( 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) ) / 𝑥 ) + 9 ( 4 / 𝑥 ) + ( ( 9 + 𝑥 ) / 𝑦 )
2.9 3 of 4 109
Arithmetic Expressions
Explanation
( 9 * (( 4 / 𝑥 ) +( ( 9 + 𝑥 ) / 𝑦 ) ) )
( ( 3 + (4 ∗ 𝑥) ) / 5 ) − ( ( 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) ) / 𝑥 ) + 9 ( 4 / 𝑥 ) + ( ( 9 + 𝑥 ) / 𝑦 )
Expression
( ( 3 + (4 ∗ 𝑥) ) / 5 ) − ( ( 10 ∗ ( 𝑦 – 5 ) ∗ ( 𝑎 + 𝑏 + 𝑐 ) ) / 𝑥 ) + ( 9 ∗ (( 4 / 𝑥 ) + ( ( 9 + 𝑥 ) / 𝑦 ) ) )
2.9 4 of 4 110
How to Evaluate an Expression
• You can safely apply the arithmetic rule for evaluating a
Python expression.
1. Operators inside parenthesis are evaluated first.
▪ Parenthesis can be nested
▪ Expression in inner parenthesis is evaluated first
2. Use operator precedence rule.
▪ 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.
2.9 111
How to Evaluate an Expression
• Example of how an expression is evaluated:
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
2.9 112
Check Point
#8
How would you write the following arithmetic expression in
Python?
4 3 + 𝑑(2 + 𝑎)
− 9 𝑎 + 𝑏𝑐 +
3(𝑟 + 34) 𝑎 + 𝑏𝑑
➢ Solution:
(4 / (3 * (r + 34))) - (9 * (a + (b * c))) + ((3 + (d * (2 + a))) / (a + (b * d)))
2.9 113
Check Point
#9
Suppose m and r are integers. Write a Python expression
for 𝑚𝑟 2 .
➢ Solution:
m * (r ** 2)
2.9 114
2.10. Augmented Assignment
Operators
▪ Check Point #10
115
Augmented Assignment Operators
• Very often the current value of a variable is used, modified,
and then reassigned back to the same variable.
• For example, the following statement increases the variable
count by 1:
count = count + 1
• Python allows you to combine assignment and addition
operators using an augmented (or compound) assignment
operator.
• For example:
count += 1
2.10 116
Augmented Assignment Operators
2.10 117
Caution
• There are no spaces in the augmented assignment
operators.
• For example, + = should be +=
2.10 118
Note
• The augmented assignment operator is performed last
after all the other operators in the expression are
evaluated.
• Example:
x /= 4 + 5.5 * 1.5
is same as
x = x / (4 + 5.5 * 1.5)
2.10 119
Check Point
#10
Assume that a = 1, and that each expression is independent.
What are the results of the following expressions?
• a += 4 5
• a -= 4 -3
• a *= 4 4
• a /= 4 0.25
• a //= 4 0
• a %= 4 1
• a = 56 * a + 6 62
2.10 120
2.11. Type Conversions and Rounding
▪ Type Conversions
▪ int(…)
▪ round(…)
▪ Int(...) vs. eval(...)
▪ str(…)
▪ Problem 7: Keeping Two Digits After Decimal Points
▪ Check Point #11 - #12
121
Type Conversions
• Can you perform binary operations with operands of different
numeric types?
◦ Meaning, can we add an integer literal with a floating-point literal?
• Yes. If an integer and a float are involved in a binary operation,
Python automatically converts the integer to a float value.
• Example: 3 * 4.5 is the same as 3.0 * 4.5
• This is called type conversion.
2.11 122
int(…)
• 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:
>>> value = 5.6
>>> int(value)
5
>>>
2.11 123
round(…)
• You can also use the round function to round a number to the
nearest whole value. For example:
>>> value = 5.6 #Odd >>> value = 6.6 #Even
>>> round(value) >>> round(value)
6 7
>>> round(5.5) >>> round(6.5)
6 6
>>> round(5.3) >>> round(6.3)
5 6
>>> round(-3.5) >>> round(-6.5)
-4 -6
>>> round(-3.4) >>> round(-6.6)
-3 -7
• If the number you are rounding is odd and followed by decimal >= 5, Python rounds the number up.
• If the number you are rounding is even and followed by decimal > 5, Python rounds the number up.
• Otherwise, Python rounds the number down.
2.11 124
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:
2.11 125
Note
• If you would like to change the variable being converted by the
functions int and round, reset the variable after invoking the
function.
• For example, value is changed after invoking the function in the
following code:
2.11 126
Int(...) vs. eval(...)
• 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.
2.11 127
Int(...) vs. eval(...)
• However, there is a subtle “gotcha” for using the eval function.
❖ The definition of gotcha is “a misfeature of a system, especially a programming language
or environment, that tends to breed bugs or mistakes because it is both enticingly easy to
invoke and completely unexpected and/or unreasonable in its outcome.” (Hyper
Dictionary)
2.11 128
str(…)
• You can use the str(value) function to convert the numeric
value to a string. For example:
>>> value = 5.6
>>> str(value)
'5.6'
>>> value
5.6
>>> value = str(value)
>>> value
'5.6'
• Note: The functions str does not change the variable being
converted.
2.11 129
Keeping Two Digits After Decimal Points
Program 7
Write a program to get a purchase amount from the user. Then
your program should calculate and display the sales tax (6%) with
two digits after the decimal point.
• Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
2.11 137
Check Point
#12
Are the following statements correct? If so, show their printout.
1 value = 4.6 ✔
2 print(int(value)) ✔(4)
3 print(round(value)) ✔(5)
4 print(eval("4 * 5 + 2")) ✔ ( 22 )
5 print(int("04")) ✔(4)
6 print(int("4.5")) ❌
7 print(eval("04")) ❌
2.11 138
2.12. Case Study: Displaying the
Current Time
▪ Problem 8: Displaying Current Time
139
Displaying Current Time
Program 8
Write a program that displays current time in Greenwich Mean
Time (GMT) in the format hour:minute:second such as 1:45:19.
Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
148
Software Development Process
2.13 149
Requirement Specification
Requirement A formal process that seeks to understand the
Specification
problem and document in detail what the
System software system needs to do. This phase
Analysis involves close interaction between users and
designers.
System
Design
Implementation
Testing
2.13 150
System Analysis
Requirement
Specification Seeks to analyze the business process in terms
of data flow, and to identify the system’s input
System
Analysis and output.
System
Design
Implementation
Testing
2.13 151
System Design
Requirement
Specification The process of designing the system’s
components.
System
Analysis
System
Design
Implementation
Testing
2.13 152
IPO
Requirement
Specification
System
Analysis Input, Process, Output
System
Design
Implementation
Testing
Deployment
The essence of system analysis and design is
input, process, and output. This is called IPO.
Maintenance
2.13 153
Implementation
Requirement
Specification
The process of translating the system design
System into programs. Separate programs are written
Analysis for each component and put to work together.
System
Design
Implementation
Testing
2.13 154
Testing
Requirement
Specification
Ensures that the code meets the
System
requirements specification and weeds
Analysis out bugs.
System
Design
Implementation
Testing
Deployment
An independent team of software engineers
not involved in the design and implementation
of the project usually conducts such testing. Maintenance
2.13 155
Deployment
Requirement
Specification
Deployment makes the project available for use.
System
Analysis
System
Design
Implementation
Testing
Deployment
Maintenance
2.13 156
Maintenance
Requirement
Specification
Maintenance is concerned with changing and
System improving the product.
Analysis
System
Design
Implementation
Testing
2.13 157
Example
• To see the software development process in action, we will
now create a program that computes loan payments. The loan
can be a car loan, a student loan, or a home mortgage loan.
• For an introductory programming course, we focus on
requirements specification, analysis, design, implementation,
and testing.
2.13 158
Computing Loan Payments
Program 9
Write a program that lets the user enter the annual interest rate,
number of years, and loan amount, and computes monthly
payment and total payment.
• So, the input needed for the program is the annual interest
rate, the length of the loan in years, and the loan amount.
172
Computing Distances
Program 10
Write a program that prompts the user to enter two points,
computes their distance, and displays the result.
Remember:
◦ Phase 1: Problem-solving
◦ Phase 2: Implementation
𝑎 0.5 = 𝑎
𝑎 2 =𝑎 × 𝑎
177
Test Questions
• Do the test questions for this chapter online at
https://liveexample-ppe.pearsoncmg.com/selftest/selftestpy?chapter=2
178
Programming Exercises
• Page 55 – 60:
◦ 2.1 – 2.8
◦ 2.10
◦ 2.12 - 14
◦ 2.16 - 2.17
179