chapter 2 input, processing and output

29
Chapter 2 Input, Processing and Output Mrs. Hong Sun COSC 1436 Summer, 2016 June 9, 2016

Upload: others

Post on 23-Jan-2022

6 views

Category:

Documents


0 download

TRANSCRIPT

Chapter 2

Input, Processing and Output

Mrs. Hong Sun

COSC 1436 Summer, 2016

June 9, 2016

Designing a Program

• Designing a Program o Programs must be carefully designed before they

are written. Before beginning a program, you must have a firm idea of what the program should produce and what data is needed to produce that output. So programmers need to define the output and data flows , develop the logic to get to that output.

o Programmers can use tools such as pseudocode and flowchart to create models of programs

Designing a Program

• Designing a Program -- Tools o Pseudocode is an artificial and informal language

that helps programmers develop algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool.

o The rules of Pseudocode are reasonably straightforward. All statements showing "dependency" are to be indented. These include while, do, for, if, switch

o The pseudocode can be translated directly to actual code.

Designing a Program

• Designing a Program -- Tools

o an example of pseudocode to create a program to add 2 numbers together and then display the result.

Start Program Enter two numbers, A, B Add the numbers together Print Sum End Program

Designing a Program

• Designing a Program -- Tools

o another example of pseudocode to compute the perimeter of a rectangle:

Start Program

Enter length, l Enter width, w Compute Perimeter = 2*l + 2*w Display Perimeter of a rectangle

End Program

Designing a Program

• Designing a Program – Use flowchart

Designing a Program

• Designing a Program – Use flowchart

Oval called terminal (appear at top and bottom)

Parallelogram called input and output symbol

Rectangle called processing symbol (performs some steps on data, such as calculation)

Designing a Program

• Designing a Program – Summary

o The process of designing a program can be summarized in the following two steps

Understand the task that the program is to perform

Determine the steps that must be taken to perform the task.

Input, Processing, and Output

• Input o the information entered into a computer system, examples

include: typed text, mouse clicks, etc.

• Processing o -the process of transforming input information into and output.

• Output o the visual, auditory, or tactile perceptions provided by the

computer after processing the provided information. Examples include: text, images, sound, or video displayed on a monitor or through speaker as well as text or Braille from printers or embossers.

print function, Comments, Variables

• print function print("Hong Sun") Output: Hong Sun

Where “Hong Sun” is string. String can be enclosed in single or double quote.

Where print is function. Perhaps the most fundamental build-in function is print function, which displays output on the screen.

A function is a piece of code in a program. The function performs a specific task. The advantages of using functions are:

• Reducing duplication of code

• Decomposing complex problems into simpler pieces

• Improving clarity of the code

• Reuse of code

• Information hiding

print function, Comments, Variables

• Some of python’s escape characters

\n \\ Backslash (\)

\' Single quote (')

\" Double quote (")

\n ASCII Linefeed (LF)

\t ASCII Horizontal Tab (TAB)

print function, Comments, Variables

• More about print string output

print ("HongSun") output: HongSun

print ("Hong\\Sun") output: Hong\Sun

print ("Hong\'Sun") output: Hong’Sun

print ("Hong\"Sun") output: Hong”Sun

print ("Hong\tSun") output: Hong Sun

print ("Hong\nSun") output: Hong

Sun

print function, Comments, Variables

• More about data print output

print("""I'm reading "Hamlet" tonight""")

Output : I'm reading "Hamlet" tonight

print function, Comments, Variables

• print function’s ending The print function normally display a line of output.

Two print sentences will produce two lines of output print(‘One’) print(‘Two’) Output is: One Two If you want to suppress the newline

print(‘One’, end=‘ ‘) print(‘Two’) Output is: One Two

print function, Comments, Variables

• print function specifying an item separator print (‘One’, ’Two’ , ’Three’) when multiple arguments are passed to the print function, they are automatically separated by space. So the output is One Two Three print (‘One’, ’Two’ , ’Three’, sep=‘’) print (‘One’, ’Two’ , ’Three’, sep=‘##’) print (‘One’, ’Two’ , ’Three’, sep=‘---’) print (‘One’, ’Two’ , ’Three’, sep=‘***’)

print function, Comments, Variables

• print function Displaying Multiple Items with + Operator

print(‘This is ‘ + ‘a cat’) Output: This is a cat.

print(‘The print function will prints as strings everything ‘ +\ ‘in a comma-separated sequence of expressions, ‘ +\ ‘and it will separate the results with single blanks by default. ‘ +\ ‘Note that you can mix types: anything that is not already a string is’ +\ ‘automatically converted to its string representation.’)

print function, Comments, Variables

• Comments Comments are note of explanation that document line or section of a program. Comments are part of the program, but the python interpreter ignores them. They are intended for people may be reading the source code. In Python, comment begins with # character. example: # This program uses print function to display output. print(‘this is my first Python project!!’)

Print function, Comments, Variables

• Variables A variable is a name that represents a value stored in the computer. Naming Rules:

• Can not use one of Python’s key words as a variable name. • A variable name can not contains space. • The first character must be one of the letters a through z , A through Z or under-score character(_) • After the first character you may use one of the letters a through z , A

through Z , the digit 0 through 9 or under-score character(_) • Variable name is case sensitive. This means the variable name Lastname is not the same as lastname.

Print function, Comments, Variables

• List of Python keywords o The following is a list of keywords for the Python

programming language.

and, del, from, not, while, as, elif, global, or, with assert, else, if, pass, yield, break, except, import, print class, exec, in, raise, continue, finally, is, return, def, for, lambda, try

o Python is a dynamic language. It changes during time. The list of keywords may change in the future.

Print function, Comments, Variables

• Variable Assignment use an assignment statement to create a variable and make it reference a piece of data. example: price = 12.25 # this is float (float) age = 25 # this is integer (int) name = ‘Hong Sun’ # this is string (str) An assignment statement is written in the following general format: variable = expression print(price, age, name)

print function, Comments, Variables

• Variable – reading input from keyboard use input function to read user input. Example: name = input(‘Enter your name:’) #Note: the input function always returns the user’s input as a string, even if the user enters a numeric data. string_hours = input(‘how many hours did you work for week?’) hours = int(string_hours) , hours = float(string_hours) or hours = int(input(‘how many hours did you work for week?’)) hours = float(input(‘how many hours did you work for week?’)) int , float called data conversion function.

print function, Comments, Variables

• Performing Calculations • Python math Operators:

Symbol Name

+ Addition

- Subtraction

* Multiplication

/ Division

// Integer Division

% Reminder

** Power

print function, Comments, Variables

• Performing Calculations # Python Source code a = 10.89234 b = 11 c = 12 add = a + b + c sub = c - a mult = a * b div = c / 3 power = a ** 2 print add, sub, mult, div print power

print function, Comments, Variables

• Formatting Numbers. x = 1234.56789 # this is float data # Two decimal places of accuracy print(format(x, '0.2f')) # Right justified in 10 chars, one-digit accuracy print(format(x, '>10.1f')) # Left justified print(format(x, '<10.1f')) # Centered print(format(x, '^10.1f')) # Inclusion of thousands separator print(format(x, ',.1f')) print(format(x, '0,.1f'))

print function, Comments, Variables

• Functions we learn today print -- output function Input -- data input function int -- data conversion function float -- data conversion functions str -- data conversion functions format – data formatting function

Programming Exercise 12.Stock Transaction program page 79

Last month Joe purchased some stock in Acme Software, Inc. here are the details of the purchase: • The number of shares that Joe purchased was 2,000 • When joe purchased the stock, he paid $40.00 per share • Joe paid his stockbroker a commission that amounted to 3% of the

amount he paid for the stock.

Two weeks later joe sold the stock. Here are the details of the sale: • The number if shares that Joe sold was 2,000 • He sold the stock for $42.75 per share • He paid his stockbroker another commission that amount to 3% of

the amount he received for the stock.

Programming Exercise 12.Stock Transaction program page 79

Write a program that display the following information: • The amount of money joe paid for the stock • The amount of Commission Joe paid for his broker

when he bought the stock • The amount of money Joe sold for the stock • The amount of Commission Joe paid for his broker

when he sold the stock • Display the amount of money that Joe had left when

he sold the stock and paid his broker(both times). If this amount is positive, then Joe made a profit. If the amount is negative, then Joe lost money.

Programming Exercise 12.Stock Transaction program page 79

buy_share=2000 # this variable is integer buy_per_share=40 # this variable is integer buy_Commission_rate=0.03 # this variable is float sold_share=2000 # this variable is integer sold_per_share=42.75 # this variable is float sold_commission_rate=0.03 # this variable is float buy_amount=buy_share*buy_per_share # this variable is integer buy_Commission = buy_amount*buy_Commission_rate # this variable is float sold_amount = sold_share*sold_per_share # this variable is float sold_Commission = sold_amount*sold_commission_rate # this variable is float # this variable final_amount is float final_amount= sold_amount-buy_amount-buy_Commission-sold_Commission print ('The amount of money Joe paid for the stock is $',format(buy_amount,',d'),sep='') print("The amount of Commission Joe paid for his broker when he bought the stock is $",format(buy_Commission ,',.0f'),sep='') print("The amount of money Joe the stock is $",format(sold_amount,',.0f'),sep='') print("The amount of Commission Joe paid for his broker when he sold the stock is $",format(sold_Commission,',.0f'),sep='') print("The amount of money Joe got is $" ,format(final_amount,',.0f'),sep='') if final_amount>0 : print("Joe made a profit") else: print("Joe lost money")

Lab exercise and Assignment

• Exercises Review Questions p73-p74

Programming Exercises 3 , 7

• Assignments:

• Programming Exercises – 1,4,5,9

– Send source code and output to [email protected] or [email protected]

– Due: June 14, 2016.