Input, Processing, and Output Joan Boone jpboone@email.unc.edu - - PowerPoint PPT Presentation

input processing and output
SMART_READER_LITE
LIVE PREVIEW

Input, Processing, and Output Joan Boone jpboone@email.unc.edu - - PowerPoint PPT Presentation

INLS 560 Programming for Information Professionals Input, Processing, and Output Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 Topics Part 1 Program design and development Variables and print statement Part 2 Reading


slide-1
SLIDE 1

Slide 1

Input, Processing, and Output

Joan Boone

jpboone@email.unc.edu

Summer 2020

INLS 560

Programming for Information Professionals

slide-2
SLIDE 2

Slide 2

Topics

Part 1

  • Program design and development
  • Variables and print statement

Part 2

  • Reading input from the keyboard
  • Calculations, data conversion

Part 3

  • Formatting, expressions
slide-3
SLIDE 3

Slide 3

Topics

Part 1

  • Program design and development
  • Variables and print statement
slide-4
SLIDE 4

Slide 4

Program Development Cycle

Iterative process: Design, code, test, fix, repeat as needed

Source: Starting Out with Python by Tony Gaddis Correct runtime and logic errors Design the program Write the code Correct syntax errors Test the program

slide-5
SLIDE 5

Slide 5

Designing a Program

  • Understand the task: what are the requirements?
  • Define the steps: what is the algorithm?

– Methods for documenting an algorithm:

pseudocode and flowcharts Example: Calculate and display the gross pay

  • f an hourly employee

Source: Starting Out with Python by Tony Gaddis

Pseudocode

  • Get the number of hours worked
  • Get the hourly pay rate
  • Multiply number of hours worked by hourly

pay rate

  • Display the result

Flowchart

slide-6
SLIDE 6

Slide 6

Basic Program Structure

INPUT

hours_worked = 40 hourly_pay_rate = 25.00 gross_pay = hours_worked * hourly_pay_rate print(gross_pay)

1000.0

PROCESS OUTPUT

slide-7
SLIDE 7

Slide 7

Variables, Values, and Types

A variable is a name that represents a value stored in the computer's memory.

  • Variables are created with an assignment statement.
  • Assigned values are often strings or numbers

message = “some useful text goes here” voting_age = 18 pi = 3.1415926535897932

Values have different types

  • string (sequence of text characters)
  • integer (numbers without a fractional portion)
  • float (numbers with a decimal point that represents fraction)
slide-8
SLIDE 8

Slide 8

Variable Naming Conventions

  • Begin with a lowercase letter, e.g. zipcode
  • Can be of arbitrary length
  • Should be descriptive – use multiple words, if applicable.

Two approaches for multi-word variables

– Use underscore, _, to separate multiple words, e.g.,

miles_per_gallon (snake_case)

– Use mixed case, e.g., milesPerGallon (camelCase)

  • Can contain both letters and numbers, e.g.,

totals_for_2019

  • Case is significant! zip_code, zipCode and zipcode

are different variables

  • Use all capital letters for constants, e.g., DAYS_IN_WEEK

Do not use Python keywords as variable names

slide-9
SLIDE 9

Slide 9

Variables in Assignment Statements

# Create two variables: top_speed and distance top_speed = 160 distance = 300 # Display the value referenced by the variables print('The top speed is') print(top_speed) print('The distance traveled is') print(distance) # Variables can appear on both sides # of an assignment statement counter = 0 counter = counter + 1 print('The counter value is') print(counter)

variable_demo1.py The top speed is 160 The distance traveled is 300 The counter value is 1 Output

slide-10
SLIDE 10

Slide 10

Display multiple items with print

# Create two variables: top_speed and distance top_speed = 160 distance = 300 # Display the value referenced by the variables print('The top speed is', top_speed) print('The distance traveled is', distance) # Variables can appear on both sides of an assignment statement counter = 0 counter = counter + 1 print('The counter value is', counter)

variable_demo2.py The top speed is 160 The distance traveled is 300 The counter value is 1 Output

slide-11
SLIDE 11

Slide 11

Multiple Ways to Display Output with print

  • print function displays a line of output, and then prints a newline

character that is not visible, but causes output to start on a new line.

  • Example

print('One') print('Two') print('Three')

  • Or print on same line

print('One', 'Two', 'Three')

  • Specifying an item separator

print('One','Two','Three', sep=', ') One Two Three One Two Three One, Two, Three

Gaddis: Section 2.8

slide-12
SLIDE 12

Slide 12

Displaying Output with Escape Characters

Python documentation on Lexical Analysis

print('One\nTwo\nThree')

One Two Three

print('Three\tFour\tFive')

Three Four Five

print('Monty Python\'s Flying Circus')

Monty Python's Flying Circus

slide-13
SLIDE 13

Slide 13

Style Guidelines and Comments

PEP 8 - Style Guide for Python Code

  • To improve readability and consistency
  • Comments: Block and inline (start with '# ')

– Why important?

  • Describe the purpose of the program
  • Describe/clarify the purpose of complex functions and formulas;

don't over-comment

  • Use for attribution

– Bad comments are worse than no comments – Also useful for debugging: comment out sections of code to try

different approaches to solving a problem

– Multi-line comments (delimited with triple quotes) ''' Very lengthy, verbose, run-on comment goes here. '''

slide-14
SLIDE 14

Slide 14

Topics

Part 2

  • Reading input from the keyboard
  • Calculations, data conversion
slide-15
SLIDE 15

Slide 15

Reading Input from Keyboard

input(prompt)is a built-in Python function that reads input typed by the user on the keyboard. Example

first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Hello', first_name, last_name)

Example output: Hello Monty Python

How it works: when the input statement is executed by Python

  • the prompt is displayed, and the program waits for you to type

something

  • when you press Enter, whatever you typed is assigned to the

variable as a string

string_input.py

slide-16
SLIDE 16

Slide 16

Gross Pay Calculation

# Prompt for hours worked hours_worked = input('Enter hours worked: ') # Prompt for hourly pay rate hourly_pay_rate = input('Enter hourly pay rate: ') # Calculate gross pay and display result gross_pay = hours_worked * hourly_pay_rate print('Gross pay: ', gross_pay)

gross_pay_calc.py Enter hours worked: 40 Enter hourly pay rate: 25 Traceback (most recent call last): File ".../gross_pay_calc.py", line 8, in <module> gross_pay = hours_worked * hourly_pay_rate

TypeError: can't multiply sequence by non-int of type 'str'

Process finished with exit code 1 Output in the PyCharm Run Window

slide-17
SLIDE 17

Slide 17

Converting Data

Use Python built-in functions that convert data to another type.

General syntax: int(item)converts item to an int (integer, or whole number)

float(item)converts item to a float (number w/decimal point)

Examples: converting strings to numeric

days_in_week = int('7')

pi = float('3.1416')

Rule: item must be a number, or a string containing a

number, otherwise an error (exception) is generated

slide-18
SLIDE 18

Slide 18

Converting User Input Strings to Numbers

hours_worked = input('Enter hours worked: ') hours_worked = float(hours_worked)

This can also be written as a nested function call:

hours_worked = float(input('Enter hours worked: '))

After the input function executes, it will return the value you entered, as a string. That value is saved (temporarily) by Python, and then is passed as an argument to the float function which converts it to a number.

slide-19
SLIDE 19

Slide 19

Exercise: Gross Pay Calculation

Enter hours worked: 40 Enter hourly pay rate: 25 Gross pay: 1000.0 Process finished with exit code 0

Output in the PyCharm Run Window

Update gross_pay_calc.py so that it converts the user inputs to float before calculating the gross pay amount.

slide-20
SLIDE 20

Slide 20

Performing Calculations: Math operators

Symbol Operation Description

+

Addition Adds two numbers

  • Subtraction

Subtracts one number from another

*

Multiplication Multiplies one number by another

/

Division Divides one number by another and gives the result as a floating point number

//

Integer division Divides one number by another and gives the result as an integer

%

Remainder Divides one number by another and gives the remainder

**

Exponent Raises a number to a power

slide-21
SLIDE 21

Slide 21

Exercise: Sale Price Calculation

  • Calculate the price of an item with a 20% discount
  • Apply a 4.75% sales tax for the total price

# Prompt for the price

  • riginal_price = float(input("Enter the item's original price: "))

# Calculate the sale_price with a 20% discount # Calculate the total_price = sale_price + tax # Display sale and total prices print('The sale price is ', sale_price) print('The total price is', total_price) sale_price.py Enter the item's original price: 100.00 The sale price is 80.0 The total price is 83.8

Sample output

slide-22
SLIDE 22

Slide 22

When the result looks like 83.80000000000001

  • Remember that all data is represented in binary
  • When a decimal fraction is converted to binary, it can't always be

converted exactly

  • For example, when 1/3 is calculated in binary, the resulting

decimal version looks like 0.3333333333333333

  • You can't predict whether the fractional portion will have 2 digits or

16, but you can control how many digits are displayed Specify a minimum field width with a format specifier (Section 2.8)

some_number = 12345.6789 print(format(some_number, '12.2f')) Result: 12345.68

Displays the number in a field of 12 spaces, with 2 decimal places

slide-23
SLIDE 23

Slide 23

Topics

Part 3

  • Formatting, expressions
slide-24
SLIDE 24

Slide 24

Example using Format Specifier

# This program displays the following floating-point numbers # in a column with their decimal points aligned. num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 # Display each number in a field # of 7 spaces with 2 decimal places. print(format(num1, '7.2f')) print(format(num2, '7.2f')) print(format(num3, '7.2f')) print(format(num4, '7.2f')) print(format(num5, '7.2f')) print(format(num6, '7.2f')) 127.90 3465.15 3.78 264.82 88.08 800.00

Result:

slide-25
SLIDE 25

Slide 25

Operator Precedence

Given: result = 12.0 + 6.0 / 3.0 What is the value of result? Python uses the same rules of precedence for evaluating expressions that you learned in math class

  • Operations in parentheses are performed first
  • Operators with the higher precedence are applied first
  • Precedence of math operators, from highest to lowest:

– Exponentiation: ** – Multiplication, division, and remainder: * / // % – Addition and subtraction: + -

slide-26
SLIDE 26

Slide 26

Mixed Type Expressions

  • When you perform a math operation, the data type of the

result will depend on the data type of the operands

  • Rules

– When both operands are int, the result is an int – When both operands are float, the result is a float – When one operand is an int and the other is a float,

the result is a float

  • Examples

– 12 * 2 → 24 – 12.0 * 2.0 → 24.0 – 12 * 2.0 → 24.0

slide-27
SLIDE 27

Slide 27

Converting Math Formulas to Programming Statements

Algebraic Expression Python Statement

Area of a triangle

A = 1/2bh

area_of_triangle = base * height / 2 Simple interest

I = prt

simple_interest = principal * rate * time Compound interest A = P (1 + R)n amount = principal * (1 + rate)**time Distance between 2 points A = P (1 + R)n distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5

Some Math Formulas can be simplified with the use of Python built-in Math functions

slide-28
SLIDE 28

Slide 28

Coin Conversion Program

  • For a given number of pennies, convert to:

dollars, quarters, dimes, nickels, and pennies

  • For example, the prompt and output might be:

Enter number of pennies: 573 Here is the amount in dollars and coins Dollars: 5 Quarters: 2 Dimes: 2 Nickels: 0 Pennies: 3

coin_conversion.py

slide-29
SLIDE 29

Slide 29

Exercise:

Convert Seconds to hours, mins, secs

  • For a given number of seconds, convert this number to

hours, minutes, and seconds

  • For example, the prompt and output might be:

Enter number of seconds: 123456 Hours: 34 Minutes: 17 Seconds: 36

print(format(hours,'02d'), format(minutes,'02d'), format(remaining_seconds,'02d'), sep=':')

'02d' displays the number with 2 decimal digits, and inserts a leading 0

if there is only 1 digit

Another way to format the results 34:17:36