Lecture02 03
Lecture02 03
Lecture 2-3
Input, Processing, and Output
2
Topics
• Designing a Program
• Input, Processing, and Output
• Displaying Output with print Function
• Comments
• Variables
• Reading Input from the Keyboard
• Performing Calculations
• More About Data Output
• Named Constants
3
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
4
Pseudocode
• Pseudocode: fake code
• Informal language that has no syntax rule
• Not meant to be compiled or executed
• Used to create model 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
7
Pseudocode (cont’d.)
• For example, suppose you have been asked to write a
program to calculate and display the gross pay for an
hourly paid employee.
• Here are the steps that you would take:
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
8
Flowcharts
• Flowchart: 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
9
10
ASCII Features
• 7-bit code
• 8th bit is unused (or used for a parity bit)
• 27 = 128 codes
• Two general types of codes:
• 95 are “Graphic” codes (displayable on a console)
• 33 are “Control” codes (control features of the console or
communications channel)
Standard ASCII code (in decimal) 13
• Script mode
18
Comments
• Comments: notes of explanation within a program
• Ignored by Python interpreter
• Intended for a person reading the program’s code
• Begin with a # character
• End-line comment: appears at the end of a line of code
• Typically explains the purpose of that line
24
Comments (cont’d)
25
Comments (cont’d)
26
Variables
• Variable: name that represents a value stored in the
computer memory
• Used to access and manipulate data stored in memory
• A variable references the value it represents
• Assignment statement: used to create a variable and
make it reference data
• General format is variable = expression
• Example: age = 25
• Assignment operator: the equal sign (=)
27
Variables (cont’d.)
• In assignment statement, variable receiving value must
be on left side
Example
29
Example
30
Variable Reassignment
• Variables can reference different values while program
is running
• Garbage collection: removal of values that are no longer
referenced by variables
• Carried out by Python interpreter
• A variable can refer to item of any type
• Variable that has been assigned to one type can be reassigned
to another type
33
Example
34
Numeric Data Types, Literals, and the
str Data Type
• Data types: categorize value in memory
• e.g., int for integer, float for real number, str used for
storing strings in memory
• Numeric literal: number written in a program
• No decimal point considered int, otherwise, considered float
• Some operations behave differently depending on data
type
35
Example
39
Reading Numbers with the input
Function
• input function always returns a string
• Built-in functions convert between data types
• int(item) converts item to an int
• float(item) converts item to a float
• Nested function call: general format:
function1(function2(argument))
• value returned by function2 is passed to function1
• Type conversion only works if item is valid numeric value,
otherwise, throws exception
40
Enter
41
eval()function
• The eval() function evaluates the specified expression,
if the expression is a legal Python statement, it will be
executed.
Example
49
The Exponent Operator and the
Remainder Operator
• Exponent operator (**): Raises a number to a power
• x ** y = xy
• Remainder operator (%): Performs division and returns
the remainder
• a.k.a. modulus operator
• e.g., 4%2=0, 5%2=1
• Typically used to convert times and distances, and to detect
odd or even numbers
50
51
Converting Math Formulas to
Programming Statements
• Operator required for any mathematical operation
• When converting mathematical expression to
programming statement:
• May need to add multiplication operators
• May need to insert parentheses
52
Mixed-Type Expressions and Data
Type Conversion
• Data type resulting from math operation depends on
data types of operands
• Two int values: result is an int
• Two float values: result is a float
• int and float: int temporarily converted to float,
result of the operation is a float
• Mixed-type expression
• Type conversion of float to int causes truncation of
fractional part
53
Breaking Long Statements into
Multiple Lines
• Long statements cannot be viewed on screen without
scrolling and cannot be printed without cutting off
• Multiline continuation character (\): Allows to break a
statement into multiple lines
Formatting Numbers
• Can format display of numbers on screen using built-in
format function
• Two arguments:
• Numeric value to be formatted
• Format specifier
• Returns string containing formatted number
• Format specifier typically includes precision and data type
• Can be used to indicate comma separators and the minimum field
width used to display the value
59
Example
60
Example
61
Formatting Integers
• To format an integer using format function:
• Use d as the type designator
• Do not specify precision
• Can still use format function to set field width or comma
separator
67
Magic Numbers
• A magic number is an unexplained numeric value that
appears in a program’s code. Example:
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
%-formatting
• Strings in Python have a unique built-in operation that
can be accessed with the % operator.
Program s-1
name = "Eric"
print("Hello, %s." % name)
Program Output
Hello, Eric.
73
%-formatting (cont’d)
Program s-2
name = "Eric"
age = 74
print("Hello, %s. You are %s." % (name, age))
Program Output
%-formatting (cont’d)
Program s-3
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
print("Hello, %s %s. You are %s. You are a %s.
You were a member of %s." %
(first_name, last_name, age, profession, affiliation))
Program Output
Hello, Eric Idle. You are 74. You are a comedian. You
were a member of Monty Python.
75
str.format()
• str.format() was introduced in Python 2.6. With
str.format(), the replacement fields are marked by curly
braces
Program s-4
name = "Eric"
age = 74
print("Hello, {}. You are {}.".format(name, age))
Program Output
str.format() (cont’d)
• You can reference variables in any order by referencing
their index.
Program s-5
name = "Eric"
age = 74
print("Hello, {1}. You are {0}.".format(age, name))
Program Output
str.format() (cont’d)
Program s-6
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
print(("Hello, {first_name} {last_name}. You are {age}. " +
"You are a {profession}. You were a member of {affiliation}.") \
.format(first_name=first_name, last_name=last_name, age=age, \
profession=profession, affiliation=affiliation))
Program Output
Hello, Eric Idle. You are 74. You are a comedian. You were
a member of Monty Python.
78
f-Strings
Program s-7
name = "Eric"
age = 74
print(f"Hello, {name}. You are {age}.")
Program Output
Hello, Eric. You are 74.
80
f-Strings (cont’d)
Program s-8
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
print(f"Hello, {first_name} {last_name}. You are {age}. " +
f"You are a {profession}. " +
f"You were a member of {affiliation}.")
Program Output
Hello, Eric Idle. You are 74. You are a comedian. You were
a member of Monty Python.
81
f-Strings (cont’d)
Program s-9
name = "eric"
sentence = f'{name.title()} is funny.'
print(sentence)
Program Output
Eric is funny.
82
f-Strings (cont’d)
Program s-10
x = 3.14159265
print(f'PI = {x:.2f}')
Program Output
PI = 3.14
83
f-Strings (cont’d)
Program s-11
x = 12345.6789
print(f'x = {x:,.2f}')
Program Output
x = 12,345.68
84
f-Strings (cont’d)
Program s-12
s1 = 'ab'
s2 = 'abc'
s3 = 'abcd'
s4 = 'abcde'
print(f'{s1:10}')
print(f'{s2:<10}')
print(f'{s3:^10}')
print(f'{s4:>10}')
Program Output
ab
abc
abcd
abcde
85
f-Strings (cont’d)
Program s-13
a = 5
b = 10
print(f'Five plus ten is {a + b} and not {2 * (a + b)}.')
Program Output
Summary
• This chapter covered:
• The program development cycle, tools for program design,
and the design process
• Ways in which programs can receive input, particularly from
the keyboard
• Ways in which programs can present and format output
• Use of comments in programs
• Uses of variables and named constants
• Tools for performing calculations in programs