Вы находитесь на странице: 1из 22

Starting Out with Programming Logic and Design

Lab 2: Modules
This lab accompanies Chapter 3 of Starting Out with Programming Logic & Design. Name !!!!"dam!!!!!!!!!!!!!!!!!!!!!!!

Lab 2.1 Algorithms


This lab re#uires $ou to thin% about the steps that ta%e place in a program b$ writing algorithms. &ead the following program prior to completing the lab.
A retail company must file a monthly sales tax report listing the total sales for the month and the amount of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is 2 percent. Write a program that asks the user to enter the total sales for the month. The application should calculate and display the following: The amount of county sales tax The amount of state sales tax The total sales tax (county plus state)

Step 1: '(amine the following algorithm.


. !et the total sales for the month. 2. "ultiply the total sales #y .$4 to calculate the state sales tax. %. "ultiply the total sales #y .$2 to calculate the county sales tax. 4. Add the state tax and county tax to calculate the total sales tax. &. 'isplay the calculated county tax( state tax( and total sales tax.

Step 2: )i*en a total sales of +,-./0-. answer the following 1hat is the calculated state ta(2 !1/33.33!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1hat is the calculated count$ ta(2 !!!!!451.05!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1hat is the calculated total ta(2 !!!!!!!!!!!!!!!!!16,4.3,!!!!!!!!!!!!!!!!!!!!!!

Starting Out with Programming Logic and Design

Lab 2.2 Pseudocode and Modules


Critical &e*iew " 7odule is a group of statements that e(ists within a program for the purpose of performing a specific tas%. 7odules are commonl$ called procedures. subroutines. subprograms. methods. and functions. The code for a module is %nown as a module definition. To e(ecute the module. $ou write a statement that calls it. The format for a module definition is as follows "odule name( ) )tatement )tatement *tc. *nd "odule Calling a module is normall$ done from the 7ain 8 9 module such as +all name( ) )enerall$. local *ariables should be used and arguments should be passed b$ reference when the *alue of the *ariable is changed in the module and needs to be retained. :or e(ample "odule main( ) ,eal -nteger num#er +all input'ata(num#er) +all print'ata(num#er) *nd "odule ..accepts num#er as a reference so the changed /alue ..will #e retained "odule input'ata(,eal ,ef num#er) 0um#er 1 2$ *nd "odule ..num#er does not to #e sent as a reference #ecause ..num#er is not going to #e modified "odule print'ata(num#er) 'isplay 2The num#er is 2( num#er *nd "odule ;elp <ideo Double clic% the file to *iew *ideo

Starting Out with Programming Logic and Design

This lab re#uires $ou to thin% about the steps that ta%e place in a program b$ writing pseudocode. &ead the following program prior to completing the lab.
A retail company must file a monthly sales tax report listing the total sales for the month and the amount of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is 2 percent. Write a program that asks the user to enter the total sales for the month. The application should calculate and display the following: The amount of county sales tax The amount of state sales tax The total sales tax (county plus state)

Step 1 This program is most easil$ sol*ed using =ust four *ariables. Declare the *ariables that $ou will need in the program. using the proper data t$pe and documenting the purpose. Variable Name
'eclare ,eal total)ales 'eclare ,eal countyTax 'eclare ,eal stateTax 'eclare ,eal salesTax

Purpose
)tores inputs )tores )tores )tores total sales the user calculated county tax calculated state tax calculated total tax

Step 2: )i*en the ma=or tas% in*ol*ed in this program. what modules might $ou consider including2 Describe the purpose of each module. 8&eference Defining and Calling a 7odule. page -39. Module Name
"odule input'ata () "odule calc+ounty () "odule cal)tate () "odule calTotal () "odule print'ata ()

Purpose
Allows the user to enter re3uired user input +alculate the county tax at 24 for the monthly sales +alculate the state tax at 44 for the monthly sales +alculate the total as state plus county 5rints necessary data

Step 3: Complete the pseudocode b$ writing the missing lines. 8&eference Defining and Calling a 7odule. page -3>319. "lso. when writing $our modules and ma%ing calls. be sure to pass necessar$ *ariables as arguments and accept them as reference parameters if the$ need to be modified in the module. 8&eference Passing "rguments b$ <alue and b$ &eference. page 0- ? 1/39.

Starting Out with Programming Logic and Design

"odule main () ..'eclare local /aria#les 'eclare ,eal total)ales 'eclare ,eal countyTax 'eclare ,eal stateTax 'eclare ,eal salesTax 6666666666666666666666666666666666666666666666666666 666666666666666666666666666666666666666666666666666666 666666666666666666666666666666666666666666666666666666 666666666666666666666666666666666666666666666666666666 ..7unction calls +all input'ata(total)ales) +all calc+ounty(total)ales( countyTax) +all calc)tate (total)ales( stateTax) +all calcTotal (countryTax( stateTax( totalTax) +all print'ata (countyTax( stateTax( totalTax) *nd "odule ..this module takes in the re3uired user input "odule input'ata(,eal ,ef total)ales) 'isplay 2*nter the total sales for the month.8 -nput total)ales *nd "odule ..this module calculates county tax ..total)ales can #e a /alue parameter #ecause it is not ..changed in the module. ..countyTax must #e a reference parameter #ecause it is ..changed in the module "odule calc+ounty(,eal total)ales( ,eal ,ef countyTax) countyTax 1 total)ales 9 .$2 *nd "odule ..this module calculates state tax "odule calc)tate (,eal total)ales( ,eal ,ef stateTax) stateTax 1 total)ales 9.$4 *nd "odule ..this module calculates total tax "odule calcTotal (,eal countyTax( ,eal stateTax( ,ef totalTax) totalTax 1 countyTax : stateTax *nd "odule ..this module prints the total( county( and state tax "odule 'isplay the 2The county tax is8( countyTax 'isplay 2The state tax is8 ( stateTax 'isplay 2The total tax is8 ( totalTax *nd "odule

Starting Out with Programming Logic and Design

Lab 2.3 lo!charts


Critical &e*iew The flowchart s$mbol used for a function call is a rectangle with *ertical bars on each side

;elp <ideo Double clic% the file to *iew *ideo

This lab re#uires $ou to thin% about the steps that ta%e place in a program b$ designing a flowchart. @se an application such as &aptor or <isio. &ead the following program prior to completing the lab.
A retail company must file a monthly sales tax report listing the total sales for the month and the amount of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is 2 percent. Write a program that asks the user to enter the total sales for the month. The application should calculate and display the following: The amount of county sales tax The amount of state sales tax The total sales tax (county plus state)

Step 1: Start &aptor and sa*e $our document as Lab 2-3. The .rap file e(tension will be added automaticall$. Start b$ adding a Comment bo( that declares $our *ariables. ;ere is a start to how $our Comment bo( should loo%.

Starting Out with Programming Logic and Design

Step 2: The ne(t step in $our flowchart should be to call $our methods. Clic% the Call S$mbol on the Left and Drag and Drop to the flow lines between Start and Stop. Double clic% on the Call S$mbol and t$pe the name of $our first method. :or e(ample. t$pe inputData in the 'nter Call bo(. Do not put the 8 9 when using &aptor. Clic% the Done button. " new bo( will pop up that will as% $ou to create a new tab. Clic% Aes. " new tab will be created for $our new method. Notice the new Tab called inputData.

Step 3: Continue this process to add $our additional methods. which are calcCount$89 calcState89. calcTotal89 and printData89. Step ": Clic% on the inputData tab and add the necessar$ code as identified in $our pseudocode in Lab 2.2. Bn &aptor. there is no need to pass *ariables as &eferences as in pseudocode. Aour inputData method might loo% li%e the following

Step #: Continue to code the remaining methods. which are calcCount$89 calcState89. calcTotal89 and printData89. Bf $ou happened to e(ecute $our program without completing $our program. an error will occur such as

Starting Out with Programming Logic and Design

Aour calculations methods input bo( might loo% li%e the following

Aour output data methods bo( might loo% li%e the following

Step $: "fter $our program is complete. clic% &un. then '(ecute to :inish. :or $our input. enter 6-345 as $our total monthl$ sales. Bf $our program is coded correctl$. the output should be as follows

Starting Out with Programming Logic and Design

The county tax is $ 3!".#$## The state sa%es tax is $2" &. '## The tota% tax is $ &#" .2&## ----(un )inishe*---Step %: The final step is to insert $our finished flowchart in the space below. Bnside &aptor. select :ile and the Print to Clipboard from the menu. Bnside 1ord in the space below. select 'dit and Paste. Aou will ha*e to do this for each module $ou created.

Starting Out with Programming Logic and Design

Starting Out with Programming Logic and Design

1/

Lab 2." P&thon 'ode and unctions


Critical &e*iew The code for a function is %nown as a function definition. To e(ecute the function. write a statement that calls it. To create a function. write its definition. The %e$word *e) is used before a function name. followed b$ parentheses and a colon. ;ere is the general format of a function definition in P$thon *e) )unction+name,-. statement statement etc. Calling a function is done in order to ma%e the module e(ecute. The general format is )unction+name,:unction names must be flushed to the left. Statements within a module must be aligned e*enl$ in order to a*oid s$nta( errors. Step 1: Start the BDL' 'n*ironment for P$thon. Prior to entering code. sa*e $our file b$ clic%ing on :ile and then Sa*e. Select $our location and sa*e this file as Lab2-&.py. Ce sure to include the .p$ e(tension. Step 2: Document the first few lines of $our program to include $our name. the date. and a brief description of what the program does. Description of the program should be
;This program will demonstrate /arious ways to ;use functions in 5ython.

Step 3: "fter $our documentation. add the following function definition and function call.
;This function is to welcome people to my program def welcome6message(): print <Welcome to my program using functions< print <"y name is =oe )tudent< ;This is a function call welcome6message()

Step ": Clic% &un. then &un 7odule to see $our output. Bt should loo% li%e the following

Starting Out with Programming Logic and Design

11

-'>* .2. ??? 1111111111111111111 ,*)TA,T 111111111111111111111 ??? Welcome to my program using functions "y name is =oe )tudent ???

Step #: Change $our program so that the function call is tabbed o*er. such as
;This function is to welcome people to my program def welcome6message(): print <Welcome to my program using functions< print <"y name is =oe )tudent< ;This is a function call welcome6message() #tab this line over

Step $: Clic% &un and &un 7odule again. AouDll notice that nothing is printed. This is because in P$thon. each line in a bloc% must be indented and aligned. :unction calls must be flushed to the left. and each line within a module must be aligned e*enl$. The following will cause a s$nta( error.
def my6function(): print <And now for< print <something completely< print <different.<

Step %: Since programs normall$ center around a main function. modif$ $our program so that it loo%s as follows
;The main function def main(): welcome6message()

;causes welcome6message to run

;This function is to welcome people to my program def welcome6message(): print <Welcome to my program using functions< print <"y name is =oe )tudent< ;This is the main function that starts the program in ;motion main() ;calls main

Starting Out with Programming Logic and Design

1,

Step (: "dd an additional function to $our program that is called goodb$e!message8 9. The contents of this function should print a goodb$e message. '(ecute $our program so that it wor%s and paste the final code below

)*he main +unction de+ main ,-: !elcome.message,- )causes !elcome.message to run goodb&e.message,- )causes goodb&e.message to run )*his +unction is to !elcome people to m& program de+ !elcome.message,-: print /0elcome to m& program using +unctions/ print /M& name is Adam 1auser/ de+ goodb&e.message,-: print 23oodb&e.2 )*his +unction is the main +unction that starts the program in )motion main,- )calls main

Starting Out with Programming Logic and Design

13

Lab 2.# P&thon 'ode and Variables


Critical &e*iew <ariables can either be local or global in scope. " local *ariable is created inside a function and cannot be accessed b$ statements that are outside a function. unless the$ are passed. " local *ariable that needs to be used in multiple functions should be passed to the necessar$ functions. "n argument is an$ piece of data that is passed into a function when the function is called. " parameter is a *ariable that recei*es an argument that is passed into a function. " global *ariable can be accessed b$ an$ function within the program. but should be a*oided if at all possible.

Step 1: Start the BDL' 'n*ironment for P$thon. Prior to entering code. sa*e $our file b$ clic%ing on :ile and then Sa*e. Select $our location and sa*e this file as Lab2-!.py. Ce sure to include the .p$ e(tension. Step 2: Document the first few lines of $our program to include $our name. the date. and a brief description of what the program does. Description of the program should be
;This program demonstrates how to use /aria#les and ;functions.

Step 3: "dd a function called main8 9 and a function call to main. Aour code might loo% li%e this
;This program uses functions and /aria#les ;the main function def main(): print <Welcome to the tip calculator program< print ;prints a #lank line ;calls main main()

Step ": "dd a function called inputName89 under the def main89 function. Aour code might loo% as follows
;this function inputs name def input0ame()

Starting Out with Programming Logic and Design

15

Step #: @nder $our function definition. write a statement that allows the user to enter their name. Bnside of the main function. call inputName89 and write a print statement that displa$s the name. Aour code might loo% as follows
;This program uses functions and /aria#les ;the main function def main(): print <Welcome to the /aria#le program< print ;prints a #lank line input0ame() print <@ello<( name ;this function inputs name def input0ame(): name 1 raw6input(<*nter your name: <) ;calls main main()

Step $: Compile and run $our program. Notice that when the program attempts to displa$ the name. a s$nta( error occurs. This is because name is declared as a local *ariable within the inputName8 9 function and main cannot access it. Step %: There are a couple of wa$s to fi( this error. '(amine the following code
;This program uses functions and /aria#les ;the main function def main(): print <Welcome to the /aria#le program< print ;prints a #lank line name 1 input0ame() print <@ello<( name ;this function inputs data def input0ame(): name 1 raw6input(<*nter your name: <) return name ;calls main main()

The local *ariable name is declared in main and set e#ual to whate*er the inputName8 9 function returns. Notice the return name that is at the end of the inputName8 9 function. This passes the *alue that was ta%en in bac% to main. Step (: "dd an additional function to $our program that is called input"ge8 9. The contents of this function should be structured similar to the inputName8 9 function

Starting Out with Programming Logic and Design

14

e(cepts that it as%s the user to enter their age. "dditionall$. ma%e a call to this new function such as age E input"ge8 9. Aou should also displa$ the *alue of age after the name is displa$ed. '(ecute $our program so that it wor%s and paste the final code below #This program demostrates how to use variables and #functions. #This program uses functions and variables #the main function def main(): print 'Welcome to the tip calculator program' print #prints a blank line name = input ame() print '!ello'" name age = input#ge() #this function inputs name def input ame(): name = raw$input ('%nter &our name: ') return name #this function inputs age def input#ge(): age = raw$input ('%nter &our age: ') return age #calls main main()

Starting Out with Programming Logic and Design

16

Lab 2.$ 0riting a 'omplete Program


;elp <ideo Double clic% the file to *iew *ideo

Step 1: Start the BDL' 'n*ironment for P$thon. Prior to entering code. sa*e $our file b$ clic%ing on :ile and then Sa*e. Select $our location and sa*e this file as Lab2-'.py. Ce sure to include the .p$ e(tension. Step 2: Document the first few lines of $our program to include $our name. the date. and a brief description of what the program does. Description of the program should be
Write a program that will calculate a 2$4 tip and a A4 tax on a meal price. The user will enter the meal price and the program will calculate tip( tax( and the total. The total is the meal price plus the tip plus the tax.

Step 3: "dd a function called main8 9 and a function call to main. Step ": "dd the function definition for input!meal8 9. calc!tip8 9. calc!ta(8 9. calc!total89. and print!info8 9. Aour code might loo% li%e the following
;This program uses functions and /aria#les ;the main function def main(): print <Welcome to the meal calculator program< print ;prints a #lank line ;this function will input meal price def input6meal(): ;this function will calculate tip at 2$4 def calc6tip(): ;this function will calculate tax at A4 def calc6tax(): ;this function will calculate tip( tax( and the total ;cost def calc6total(): ;this function will print tip( tax( the mealprice( and ;the total def print6info(): ;calls main

Starting Out with Programming Logic and Design


main()

1-

Step #: Bnside of main89 under the print ;prints a #lank line statement. create a local *ariable named mealprice that is set to the input!meal89 function. This should loo% li%e the following
mealprice 1 input6meal()

Step $: "dd the following lines of code inside of input!meal89 function. This should loo% li%e the following
mealprice 1 input(<*nter the meal price B<) mealprice 1 float(mealprice) return mealprice

The first line as%s the user to enter their meal price. The second line con*erts the *alue to a float. since it will li%el$ be a decimal *alue. This must be done with all potential decimal *alues that the user enters. The third line returns the input *alue of mealprice to the place where it was called 8in Step 49. Step %: Bnside of main89 under the meal 1 input6meal() statement. create a local *ariable named tip that is set to the calc!tip89 function. Bn this case. $ou must pass mealprice to the function. so it must be placed between the parentheses. This should loo% li%e the following
tip 1 calc6tip(mealprice)

Step (: "dd the following lines of code inside of calc!tip8mealprice9 function. The entire function should loo% li%e the following
def calc6tip(mealprice): tip 1 mealprice 9 .2$ return tip

The first line is the function definition. Bt accepts mealprice as a parameter. The second line is to calculate tip as ,/F of the mealprice. The third line returns the calculated tip to the place where it is called. Step 4: Bnside of main89 under the tip 1 calc6tip(mealprice) statement. create a local *ariable named ta( that is set to the calc!ta(89 function. Bn this case. $ou must pass mealprice to the function. so it must be placed between the parentheses. This should loo% li%e the following
tax 1 calc6tax(mealprice)

Step 15: "dd the following lines of code inside of calc!ta(8mealprice9 function. The entire function should loo% li%e the following

Starting Out with Programming Logic and Design

13

def calc6tax(mealprice): tax 1 mealprice 9 .$A return tax

The first line is the function definition. Bt accepts mealprice as a parameter. The second line is to calculate ta( as 6F of the mealprice. The third line returns the calculated ta( to the place where it is called. Step 11: Bnside of main89 under the tax 1 calc6tax(mealprice) statement. create a local *ariable named total that is set to the calc!total89 function. Bn this case. $ou must pass mealprice. tip. and ta( to the function. so the$ must be placed between the parentheses. This should loo% li%e the following
total 1 calc6total(mealprice( tip( tax)

Step 12: "dd the following lines of code inside of calc!total8mealprice. tip. ta(9 function. The entire function should loo% li%e the following
def calc6total(mealprice( tip( tax): total 1 mealprice : tip : tax return total

The first line is the function definition. Bt accepts mealprice. tip. and ta( as parameters. The second line is to calculate the total of all three *alues added together. The third line returns the calculated total to the place where it is called. Step 13: Bnside of main89 under the total 1 calc6total(mealprice( tip( tax) statement. call the print!info 89 function. Bn this case. $ou must pass mealprice. tip. ta(. and total to the function. so the$ must be placed between the parentheses. This should loo% li%e the following
print6info(mealprice( tip( tax( total)

Step 1": "dd the following lines of code inside of print!info8mealprice. tip. ta(. total9 function. The entire function should loo% li%e the following
def print6info(mealprice( tip( tax( total): print <The meal price is B<( mealprice print <The tip is B<( tip print <The tax is B<( tax print <The total is B<( total

The first line is the function definition. Bt accepts mealprice. tip. ta(. and total as parameters. The following lines print the mealprice. the calculated tip. the calculated ta(. and the calculated total.

Starting Out with Programming Logic and Design

10

Step 1#: &un $our module and fi( an$ errors $ou ma$ ha*e. The most common errors ma$ be that $ou ha*e misspelled something when t$ping. or that $our indentations are not aligned properl$. 1hen running $our program. enter ,5.4/ as the meal price. Aour output should loo% as follows
Welcome to the tip and tax calculator program *nter the meal price B24.&$ The meal price is B 24.& The tip is B 4.C The tax is B .4D The total is B %$.ED

Step 1$: 1hen $our program is completed and $ou ha*e tested $our output in Step 14. paste $our completed program below.

)*his program uses +unctions and 6ariables )the main +unction de+ main,-: print /0elcome to the meal calculator program/ print )prints a blan7 line mealprice 8 input.meal,tip 8 calc.tip,mealpriceta9 8 calc.ta9,mealpricetotal 8 calc.total,mealprice: tip :ta9print.in+o,mealprice: tip: ta9: total)this +unction !ill input meal price de+ input.meal,-: mealprice 8 input,/;nter the meal price </mealprice 8 +loat,mealpricereturn mealprice )this +unction !ill calculate tip at 25= de+ calc.tip,mealprice-: tip 8 mealprice > .25 return tip )this +unction !ill calculate ta9 at $= de+ calc.ta9,mealprice-:

Starting Out with Programming Logic and Design

,/

ta9 8 mealprice > .5$ return ta9 )this +unction !ill calculate tip: ta9: and the total )cost de+ calc.total ,mealprice: tip: ta9-: total 8 mealprice ? tip ? ta9 return total )this +unction !ill print tip: ta9: the mealprice: and )the total de+ print.in+o,mealprice: tip: ta9: toal-: print /*he meal price is </ :mealprice print /*he tip is </ :tip print /*he ta9 is </ :ta9 print /*he total is </ :total )calls main main,-

Starting Out with Programming Logic and Design

,1

Lab 2.% Programming 'hallenge 1 @etail *a9


;elp <ideo Double clic% the file to *iew *ideo

This lab re#uires $ou to translate $our wor% in the pseudocode and flowchart from Lab ,., and Lab ,.3 to actual code using P$thon. &ead the following program prior to completing the lab.
A retail company must file a monthly sales tax report listing the total sales for the month and the amount of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is 2 percent. Write a program that asks the user to enter the total sales for the month. The application should calculate and display the following: The amount of county sales tax The amount of state sales tax The total sales tax (county plus state)

Consider the following functions for $our program main that calls $our other functions inputData that will as% for the monthl$ sales calcCount$ that will calculate the count$ ta( calcState that will calculate the state ta( calcTotal that will calculate the total ta( printData that will displa$ the count$ ta(. the state ta(. and the total ta( Bf $our program is correct. sample output might loo% as follows
Welcome to the total tax calculator program *nter the total sales for the month B 2&AD The county tax is B 2& .%4 The state tax is B &$2.AE The total tax is B D&4.$2

*he P&thon 'ode GThis program uses functions and *ariables GThe main function def main89 print H1elcome to the total ta( calculator programH print Gprints a blan% line totalsales E inputData89

Starting Out with Programming Logic and Design count$ta( E calcCount$8totalsales9 stateta( E calcState8totalsales9 totalta( E calcTotal8count$ta(. state.ta(9 printData8count$ta(. stateta(. totalta(9 GThis function will input meal price def inputData89 totalsales E input8H'nter the total sales for the month +H9 totalsaels E float8totalsales9 return totalsales GThis function will calculate the tip at ,F def calcCount$8totalsales9 count$ta( E totalsales I ./, return count$ta( GThis function will calcualte the tip at 5F def calcState8totalsales9 stateta( E totalsales I ./5 return stateta( GThis function will calcualte tip. ta(. and the total def calcTotal8count$ta(. stateta(9 totalta( E count$ta( J stateta( return totalta( GThis function will print the tip. ta(. the mealprice. and the total def printData8count$ta(. stateta(. totalta%9 print HThe counnt$ ta( is +H. count$ta( print HThe state ta( is +H. stateta( print HThe total ta( is +H. totalta( Gcalls main main89

,,

Вам также может понравиться