CHAPTER 2
Input,
Processing,
and Output
Copyright © 2018 Pearson Education, Inc.
Designing a Program
• Programs must be designed before
they are written
• Program development cycle:
• Design the program
• Write the code
• Correct syntax errors
• Test the program
• Correct logic errors
Copyright © 2018 Pearson Education, Inc.
Designing a Program
• Design is the most important part of the
program development cycle
• Why is that?
• First, you must understand the task that the
program is to perform
• Professionals work with their customer(s) to get a
sense of what the program is supposed to do
• They ask questions about program details
• They create one or more software requirements
Copyright © 2018 Pearson Education, Inc.
Designing a Program
• Then, you determine the steps that
must be taken to perform the task
• Break down required task into a series of
steps
• Create an algorithm, listing logical steps that
must be taken
• An Algorithm is a set of well-defined
logical steps that must be taken to
perform a task
Copyright © 2018 Pearson Education, Inc.
An Algorithm for a Human
Copyright © 2018 Pearson Education, Inc. Source: [Link]
Another Algorithm for a Human?
• Group Activity:
• List the steps in another everyday human
activity.
• It can be anything.
Copyright © 2018 Pearson Education, Inc.
Another Algorithm
• What steps would you take in a program
to calculate and display the gross pay for
an hourly paid employee?
1. Get the number of hours worked.
2. Get the hourly pay rate.
3. Multiply the number of hours worked by the
hourly pay rate.
4. Display the result of the calculation that was
performed in step 3.
Copyright © 2018 Pearson Education, Inc.
Flowcharts
• Flowchart: a diagram that
graphically depicts the steps in
a program
• Ovals are terminal symbols
• Parallelograms are input and output
symbols
• Rectangles are processing symbols
• Symbols are connected by arrows
that represent the flow of the
program
Copyright © 2018 Pearson Education, Inc.
Flowcharts
• Here’s the algorithm from
above:
1. Get the number of hours worked.
2. Get the hourly pay rate.
3. Multiply the number of hours
worked by the hourly pay rate.
4. Display the result of the
calculation that was performed in
step 3.
Copyright © 2018 Pearson Education, Inc.
Flowcharts
• Group Activity:
• Create a flowchart for the human algorithm
you made earlier.
• Or make a flowchart for the human algorithm
that someone in your group created.
Copyright © 2018 Pearson Education, Inc.
Pseudocode
• Pseudocode:
• A step in the direction of formal code, but it’s
not meant to be compiled or executed
• Used to create a model for the actual program
• No need to worry about syntax errors, can focus
on program’s design
• Can be translated directly into actual code in any
programming language
Copyright © 2018 Pearson Education, Inc.
Pseudocode
• Algorithm:
1. Get the number of hours worked.
2. Get the hourly pay rate.
3. Multiply the number of hours worked by the hourly pay
rate.
4. Display the result of the calculation that was performed
in step 3.
• Pseudocode:
1. Input the hours worked
2. Input the hourly pay rate
3. Calculate gross pay as hours worked multiplied by
pay rate
4. Display the gross pay
Copyright © 2018 Pearson Education, Inc.
Pseudocode
• Group Activity:
• Create pseudocode for the human algorithm
you made earlier.
• Or write pseudocode for the human
algorithm that someone in your group
created.
Copyright © 2018 Pearson Education, Inc.
Input, Processing, and Output
• Typically, computer programs perform a three-
step process
1. Receive input - one common form is data typed on a
keyboard
2. Perform some process on the input – for example, a
mathematical calculation
3. Produce output
Copyright © 2018 Pearson Education, Inc.
Variables
• Programs store data in the computer’s main
memory (RAM) and perform operations on
that data.
• Programs use variables to access and
manipulate data that is stored in main
memory.
• A variable is a name that represents a value
in the computer’s main memory.
Copyright © 2018 Pearson Education, Inc.
Variables
• You use an assignment statement to create a variable and make it
reference a piece of data.
• Here is an example of an assignment statement: age = 72
• The equal sign (=) is known as the assignment operator.
• After this statement executes, a variable named age will be created,
and it will reference the value 72.
age
• An assignment statement is written in this general format: <variable> =
<expression>
• After an assignment statement executes, the variable listed on the left
side of the equal sign will reference the value given on the right side of
the equal sign.
Copyright © 2018 Pearson Education, Inc.
Variables are a KEY CONCEPT!
• Variables refer to locations in main
memory that contain data used by your
program!
age
Copyright © 2018 Pearson Education, Inc.
Variables
• A variable can be passed as an argument to a
function:
width = 10
print(width)
• We have reached a critical juncture!
• This is our first program!
• Lets do one of the most important things good
software developers do!
• Lets trace this code. (Also called “desk
checking”, “running code by hand” and others.)
Copyright © 2018 Pearson Education, Inc.
Variables
• You cannot use a variable until you have
assigned a value to it.
• An error will occur if you try to perform an
operation on a variable, such as printing it,
before it has been assigned a value.
Copyright © 2018 Pearson Education, Inc.
Variable Reassignment
• Variables can reference different values
while a program is running
Group
Activity:
Run this
code by
hand
Copyright © 2018 Pearson Education, Inc.
Variable Naming Rules
• Rules for naming variables in Python:
• The variable name cannot be a Python keyword
• The variable name cannot contain spaces
• The first character must be a letter (or an underscore)
• After the first character, you may use letters, digits, or
underscores
• Variable names are case sensitive
• The variable name should reflect its use
Copyright © 2018 Pearson Education, Inc.
Variable Naming Rules
Group
Activity:
Indicate
legal or not
for each
Copyright © 2018 Pearson Education, Inc.
Numeric Data Types and
Literals
• A number that is written into a program’s
code is called a numeric literal. For example,
the “3.14159” in this statement: pi = 3.14159
• There are two numeric data types:
• int for integer / whole numbers; i.e. 7, 124,
etc.
• float for real numbers; i.e. 1.5, 3.14159, etc.
Copyright © 2018 Pearson Education, Inc.
Performing Calculations
• Most real-world algorithms require calculations
to be performed.
• A programmer’s tools for performing
calculations are math operators.
Copyright © 2018 Pearson Education, Inc.
Performing Calculations
• Programmers use operators to create math
expressions.
• A math expression performs a calculation
and gives a value. For example, 12 + 2
• The values on the right and left of the +
operator are called operands. These are
values that the + operator adds together.
• Variables may also be used in a math
expression. For example, hours * pay_rate
Copyright © 2018 Pearson Education, Inc.
Performing Calculations
Group
Activity:
Run this
code by
hand
Copyright © 2018 Pearson Education, Inc.
Operator Precedence
• Consider the following statement:
• outcome = 12.0 + 6.0 / 3.0
• What value will be assigned to the variable outcome?
• Python follows the same order of operations that you learned in
math class.
• Operations that are enclosed in parentheses (P) are performed
first.
• Then, when two operators share an operand, the operator with
the higher precedence is applied first.
• The precedence of the math operators, from highest to lowest,
are:
1. Exponentiation: ** (E)
2. Multiplication, division, and remainder: * / // % (MD)
3. Addition and subtraction: + − (AS)
PEMDAS
Copyright © 2018 Pearson Education, Inc.
Mixed-Type Expressions
• When you perform a math operation on two
operands, the data type of the result will depend on
the data type of the operands.
• Two int values -> int
• Two float values -> float
• An int and a float -> float
• my_number = 5 * 2.0
• When this statement executes, the value 5 will
be converted to a float (5.0) then multiplied by
2.0.
• An expression that uses operands of different data
types is called a mixed-type expression.
Copyright © 2018 Pearson Education, Inc.
• The need to create math expressions in a program
are often driven by the nature of the problem you’re
being asked to solve.
• They are frequently word problems that are very
similar to those you worked on in elementary and
high school.
Copyright © 2018 Pearson Education, Inc.
Word Problems
• Group Activity
• Convert this word problem into a series of steps and
variables that a computer could follow:
A movie theater charges $8 per adult ticket and $5
per child ticket. If a family buys 3 adult tickets and 2
child tickets, how much do they pay?
• First, solve this problem yourself.
• And show your work.
• Then, write your solution in steps with variables.
• This isn’t Python code you’re writing; it’s your algorithm
to solve the problem.
• As always, first solve this independently.
• Then compare notes with your group.
Copyright © 2018 Pearson Education, Inc.
Word Problems
• Group Activity – Do the same with these problems:
• A person starts with $50, spends $18 on groceries, and then
earns $30 doing yard work. How much money do they have
now?
• A car travels 60 miles per hour for 2 hours, stops for 30
minutes, then travels another 30 miles. How far did it travel
total?
• A gym charges a $40 membership fee plus $10 per visit. If a
person visits fewer than 5 times in a month, they get a $10
discount. How much does someone pay if they visit 4 times?
• A printer prints 12 pages per minute. How many pages will it
print in 7 minutes?
• A rectangle has a perimeter of 30 inches. One side is 8 inches
long. What is the length of the other side?
Copyright © 2018 Pearson Education, Inc.
Strings and String Literals
• In Chapter 1, we talked about two important data types:
numbers and characters.
• A sequence of characters that is used as data is called a string.
• When a string appears in the code of a program, it is called a
string literal.
• It must be enclosed in single (') or double (") quote marks
• For instance “To be or not to be”
T o ␣ b e ␣ o r
␣ n o t ␣ t o ␣ b e
• Is this a syntactically correct string literal - ‘I’m going to work’
• “I’m going to work”
• ‘I plan to read “Hamlet”’
Copyright © 2018 Pearson Education, Inc.
The str Data Type
• In addition to the int and float data types,
Python also has a data type named str, which
is used for storing strings in memory.
Copyright © 2018 Pearson Education, Inc.
Reading Input from the
Keyboard
• Many programs need to read input from the user
• Python’s built-in input function reads input
from the keyboard
• Returns the data as a string
• Format: <variable> = input(<prompt>)
• The prompt is usually a string asking the
user to enter a value.
Copyright © 2018 Pearson Education, Inc.
Converting Strings to
Numbers
• The input function always returns a string.
• Python has built-in functions that you can
use to convert a string to a numeric type.
• This conversion only works if the item is a
valid numeric value, otherwise an exception
is thrown.
Copyright © 2018 Pearson Education, Inc.
Converting Strings to
Numbers
• For example, suppose you are writing a payroll
program and you want to get the number of hours
that the user has worked. Look at the following
code:
string_value = input('How many hours did you work? ')
hours = int(string_value)
• Suppose you want to get the user’s hourly pay
rate.
string_value = input(’What is your hourly pay rate? ')
pay_rate = float(string_value)
Copyright © 2018 Pearson Education, Inc.
String Concatenation
• We know that the + operator is used to add two
numbers. When the + operator is used with two
strings, it performs string concatenation; it appends
one string to another.
print('This is ' + 'one string.') ->
This is one string.
print('Enter the amount of ' + 'sales for each day and ' +
'press Enter.’) ->
Enter the amount of sales for each day and press Enter.
Copyright © 2018 Pearson Education, Inc.
Comments
• Comments are notes of explanation
within a program
• Ignored by the Python interpreter
• Intended for a person reading the program’s code
• Begin with a # character
Copyright © 2018 Pearson Education, Inc.
Comments
• End-line comments appear at the end
of a line of code
• Typically explains the purpose of that line
Copyright © 2018 Pearson Education, Inc.
Breaking Long Statements
into Multiple Lines
• For readability, you can break a long
statement into multiple lines by using the
line continuation character, which is a
backslash (\).
result = var1 * 2 + var2 * 3 + \
var3 * 4 + var4 * 5
Copyright © 2018 Pearson Education, Inc.
Breaking Long Statements
into Multiple Lines
• You can break any part of a statement that is
enclosed in parentheses into multiple lines
without using the line continuation character.
print("Monday's sales are", monday,
"and Tuesday's sales are", tuesday,
"and Wednesday's sales are", Wednesday)
total = (value1 + value2 +
value3 + value4 +
value5 + value6)
Copyright © 2018 Pearson Education, Inc.
Displaying Output with the
print Function
• A function is a piece of prewritten code that
performs an operation.
• Python has numerous built-in functions that perform
various operations.
• Perhaps the most fundamental built-in function is
the print function, which displays output on the
screen.
• Here is an example of a statement that executes the
print function: print('Hello world’)
• The syntax for this statement – calling a function –
is: <function name>(<argument>)
Copyright © 2018 Pearson Education, Inc.
Displaying Output with the
print Function
• Then, lets write a program that displays your name
and address on the computer screen.
• Here’s an example:
• print('Kate Austen')
• print('123 Full Circle Drive’)
• print('Asheville, NC 28899’)
• The statements in this program execute in the order
that they appear, from the top of the program to the
bottom.
Copyright © 2018 Pearson Education, Inc.
Displaying Multiple Items with
the print Function
• Python allows you to display multiple items with
a single call to print
• Items are separated by commas when passed as
arguments
• Arguments displayed in the order they are passed
to the function
• Items are automatically separated by a space
when displayed
Copyright © 2018 Pearson Education, Inc.
Python Summary
# Data Types: int, float and str
# Functions
print("Hello World")
input("Enter your name: ")
int("25")
float("3.14")
# Assignment Statements
# <variable> = <expression>
a=0
b=a+3
a=b*4
c=a/2
c=c+1
f = c * 1.1
s = "This is a string" + " " + "And this string is concatenated"
age = int(input("Enter your age: "))
Copyright © 2018 Pearson Education, Inc.
Parking Lot
Copyright © 2018 Pearson Education, Inc.
More About Data Output
• Replace the print function’s newline character
• We know that the following three statements will
produce three lines of output:
• print('One')
• print('Two')
• print('Three')
• If you do not want the print function to start a new
line of output, you can do this:
• print('One', end=' ')
• print('Two', end=' ')
• print('Three’)
• The output will be: One Two Three (on a single line)
• You can use any character with the end argument
Copyright © 2018 Pearson Education, Inc.
More About Data Output
• When multiple arguments are passed to the print
function, they are automatically separated by a
space:
• print('One', 'Two', 'Three') -> One Two Three
• If you do not want a space printed between the
items, you can use the sep argument:
• print('One', 'Two', 'Three', sep='') -> OneTwoThree
• print('One', 'Two', 'Three', sep='*') -> One*Two*Three
• You can use any character with the sep argument
Copyright © 2018 Pearson Education, Inc.
More About Data Output
(cont’d.)
• An escape character is a special character that is
preceded with a backslash (\).
• When printed, the escape characters are treated as
special commands that are embedded in the string.
• For example, \n is the newline escape character.
When the \n escape character is printed, it isn’t
displayed on the screen. Instead, it causes output to
advance to the next line.
• print('One\nTwo\nThree’) ->
• One
• Two
• Three
Copyright © 2018 Pearson Education, Inc.
More About Data Output
(cont’d.)
• The \t escape character advances the output to the next
horizontal tab position. (A tab position normally appears
after every eighth character.)
• print('Mon\tTues\tWed')
• print('Thur\tFri\tSat') ->
• Mon Tues Wed
• Thur Fri Sat
Copyright © 2018 Pearson Education, Inc.
Formatting Numbers
• You might not always be happy with the way that
numbers, especially floating-point numbers, are
displayed on the screen.
• When a floating-point number is displayed by the
print function, it can appear with up to 12 significant
digits.
Copyright © 2018 Pearson Education, Inc.
Formatting Numbers
• Because the program displays a dollar amount, it
would be nice to see that amount rounded to two
decimal places.
• We can do that, and more, with the built-in format
function.
• print(format(12345.6789, '.2f')) -> 12345.68
• The general syntax for the format function is:
• format(<numeric value>,<format specifier>)
• The .2 specifies the precision. It indicates that we
want to round to two decimal places.
• The f specifies that the data type of the number we
are formatting is a floating-point number.
Copyright © 2018 Pearson Education, Inc.
Formatting Numbers
• Here’s the same number, rounded to one decimal
place:
• print(format(12345.6789, '.1f')) -> 12345.7
• You might prefer to display floating-point numbers in
scientific notation:
• print(format(12345.6789, 'e')) -> 1.234568e+04
• print(format(12345.6789, '.2e')) -> 1.23e+04
• You might want the number to be formatted with
comma separators:
• print(format(12345.6789, ',.2f')) ->12,345.68
• print(format(123456789.456, ',.2f')) -> 123,456,789.46
• There are additional format specifiers described in
the chapter: percentage, integers, etc.
Copyright © 2018 Pearson Education, Inc.
Converting Math Formulas to
Programming Statements
• You probably remember from algebra class that the
expression 2xy is understood to mean 2 times x
times y.
• In math, you do not always use an operator for
multiplication.
• Python, as well as other programming languages,
requires an operator for any mathematical operation.
Copyright © 2018 Pearson Education, Inc.
Converting Math Formulas to
Programming Statements
• When converting some algebraic
expressions to programming expressions,
you may have to insert parentheses that do
not appear in the algebraic expression.
Copyright © 2018 Pearson Education, Inc.
Magic Numbers
• A magic number is an unexplained numeric
value that appears in a program’s code.
Example:
amount = balance * 0.069
• What is the value 0.069? An interest rate? A
fee percentage? Only the person who wrote
the code knows for sure.
Copyright © 2018 Pearson Education, Inc.
The Problem with Magic
Numbers
• It can be difficult to determine the purpose of the
number.
• If the magic number is used in multiple places in the
program, it can take a lot of effort to change the
number in each location, should the need arise.
• You take the risk of making a mistake each time you
type the magic number in the program’s code.
• For example, suppose you intend to type 0.069, but you
accidentally type .0069. This mistake will cause mathematical
errors that can be difficult to find.
Copyright © 2018 Pearson Education, Inc.
Named Constants
• You should use named constants instead of magic numbers.
• A named constant is a name that represents a value that does
not change during the program's execution.
• Example:
INTEREST_RATE = 0.069
• This creates a named constant named INTEREST_RATE,
assigned the value 0.069. It can be used instead of the magic
number:
amount = balance * INTEREST_RATE
Copyright © 2018 Pearson Education, Inc.
Advantages of Using Named
Constants
• Named constants make code self-explanatory (self-
documenting)
• Named constants make code easier to maintain
(change the value assigned to the constant, and the
new value takes effect everywhere the constant is
used)
• Named constants help prevent typographical errors
that are common when using magic numbers
Copyright © 2018 Pearson Education, Inc.
Turtle Graphics
• In the late 1960s, MIT professor Seymour Papert
used a robotic “turtle” to teach programming.
• The turtle was tethered to a computer where a
student could enter commands, causing the turtle
to move.
• The turtle also had a pen that could be raised and
lowered, so it could be placed on a sheet of paper
and programmed to draw images.
• Python has a turtle graphics system that simulates
a robotic turtle.
• You can use Python statements to move the turtle
around the screen, drawing lines and shapes.
Let’s try it!
Copyright © 2018 Pearson Education, Inc. Source: [Link]