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 input from the keyboard ● Calculations, data conversion Part 3 ● Formatting, expressions Slide 2
Topics Part 1 ● Program design and development ● Variables and print statement Slide 3
Program Development Cycle Correct Design Correct Write the Test the runtime and the syntax code program logic errors program errors Iterative process: Design, code, test, fix, repeat as needed Slide 4 Source: Starting Out with Python by Tony Gaddis
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 of an hourly employee 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 5 Source: Starting Out with Python by Tony Gaddis
Basic Program Structure INPUT hours_worked = 40 hourly_pay_rate = 25.00 PROCESS gross_pay = hours_worked * hourly_pay_rate print(gross_pay) OUTPUT 1000.0 Slide 6
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 7
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 8
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 Output # of an assignment statement counter = 0 The top speed is counter = counter + 1 160 print( 'The counter value is' ) The distance traveled is 300 print(counter) The counter value is 1 variable_demo1.py Slide 9
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) Output The top speed is 160 The distance traveled is 300 The counter value is 1 variable_demo2.py Slide 10
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') One print('Two') Two print('Three') Three ● Or print on same line One Two Three print('One', 'Two', 'Three') ● Specifying an item separator One, Two, Three print('One','Two','Three', sep=', ') Slide 11 Gaddis: Section 2.8
Displaying Output with Escape Characters 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 Python documentation on Lexical Analysis Slide 12
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 13 '''
Topics Part 2 ● Reading input from the keyboard ● Calculations, data conversion Slide 14
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 Slide 15 string_input.py
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) Enter hours worked: 40 Output in the PyCharm Run Window 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 Slide 16 gross_pay_calc.py
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 17
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 18
Exercise: Gross Pay Calculation Update gross_pay_calc.py so that it converts the user inputs to float before calculating the gross pay amount. Output in the PyCharm Run Window Enter hours worked: 40 Enter hourly pay rate: 25 Gross pay: 1000.0 Process finished with exit code 0 Slide 19
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 20
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 original_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) Sample output Enter the item's original price: 100.00 The sale price is 80.0 The total price is 83.8 Slide 21 sale_price.py
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 22
Topics Part 3 ● Formatting, expressions Slide 23
Recommend
More recommend