Solutions: Solutions Manual For Starting Out With Programming Logic and Design 5Th Edition Gaddis
Solutions: Solutions Manual For Starting Out With Programming Logic and Design 5Th Edition Gaddis
Solutions: Solutions Manual For Starting Out With Programming Logic and Design 5Th Edition Gaddis
SOLUTIONS
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Chapter 2
Multiple Choice
1. C
2. B
3. D
4. B
5. A
6. C
7. C
8. A
9. B
10. D
11. B
12. A
13. C
14. A
15. D
16. B
17. B
18. C
19. D
20. A
True or False
1. False
2. True
3. False
4. True
5. False
6. True
7. True
8. True
9. False
10. False
Short Answer
1. Interview the customer
2. An informal language that has no syntax rules, and is not meant to be compiled or
executed. Instead programmers use pseudocode to create models or “mock-ups” of
programs.
3. (1) Input is received. (2) Some process is performed. (3) Output is produced.
4. The term user-friendly is commonly used in the software business to describe programs
that are easy to use.
5. The variable’s name and data type.
6. It depends on the language being used. Each language has its own way of handling
uninitialized variables. Some languages assign a default value such as 0 to uninitialized
variables. In many languages, however, uninitialized variables hold unpredictable values.
This is because those languages set aside a place in memory for the variable, but do not
alter the contents of that place in memory. As a result, an uninitialized variable holds
the value that happens to be stored in its memory location. Programmers typically refer
to unpredictable values such this as "garbage."
Algorithm Workbench
1. Display "Enter your height."
Input height
3. a) Set b = a + 2
b) Set a = b * 4
c) Set b = a / 3.14
d) Set a = b – 8
4. a) 12
b) 4
c) 2
d) 6
7. Set count = 27
8. Set total = 10 + 14
11. 11
12. 5
Debugging Exercises
1. The variable name is enclosed in quotes. This is an error because the variable’s name
will be displayed instead of the variable’s value.
2. The first character of the variable name begins with a number. This is an error because
most programming languages do not allow variable names to begin with numbers.
3. The expression is missing parentheses. This is an error because, as the order of
operations dictates, the division will occur before the addition and the result will be
incorrect.
4. The variable is being used before it has been declared. This is an error because most
programming languages do not allow variables to be used before they are declared.
5. The variables are being used in a calculation before they have been initialized. This is an
error because uninitialized variables often contain unknown values, which will cause the
result to be incorrect.
6. The assignment statement is not in the correct format. This is an error because all
programming languages require that you write the name of the variable that is receiving
the value on the left side of the = operator.
7. A named constant cannot be assigned a value with a Set statement. This is an error
because the program attempts to change the value of a named constant.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Variable declarations
Declare Real purchase, stateTax, countyTax, totalTax, totalSale
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Calculate miles-per-gallon.
Set mpg = miles / gallons
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Start
Display "Your
Declare Real weight weight at the end
of month 2 is ",
weight
Constant Real
MONTHLY_WEIGHT_LOSS =
4 Set weight = weight –
MONTHLY_WEIGHT_LOSS
Display "Enter
your starting Display "Your
weight." weight at the end
of month 3 is ",
weight
Input weight
Set weight = weight –
MONTHLY_WEIGHT_LOSS
Display "Your
weight at the end
of month 5 is ",
weight
Display "Your
weight at the end
of month 6 is ",
weight
End
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Declare variables
Declare Real payment // Monthly payment amount
Declare Real total // Total payments
Declare Integer months // Number of months
Start
End
Display "Enter
the amount paid
each month."
Input payment
Display "Enter
the number of
months."
Input months
// Declare variables
Declare Integer pizzas // Number of pizzas
Declare Integer slicesPerPizza // Slices per pizza
Declare Integer totalSlices // Total number of slices
Declare Integer people // Number of people
Declare Integer leftover // Number of leftover slices
Start
Display "How
Declare Integer pizzas many people are
Declare Integer slicesPerPizza coming?"
Declare Integer totalSlices
Declare Integer people
Declare Integer leftover
Input people
Constant Integer
SLICES_PER_PERSON = 3
Input pizzas
Display "There
will be ", leftover,
" leftover slices."
Display "How
many slices per
pizza?"
End
Input
slicesPerPizza
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Named constants
Constant Real COMMISSION_RATE = 0.02
Constant Integer NUM_SHARES = 1000
Constant Real PURCHASE_PRICE = 32.87
Constant Real SELLING_PRICE = 33.92
// Variables
Declare Real amountPaidForStock // Amount paid for the stock
Declare Real purchaseCommission // Commission paid to purchase stock
Declare Real totalPaid // Total amount paid
Declare Real stockSoldFor // Amount stock sold for
Declare Real sellingCommission // Commission paid to sell stock
Declare Real totalReceived // Total amount received
Delcare Real profitOrLoss // Amount of profit or loss
// Calculate the amount that Joe paid for the stock, not
// including the commission.
Set amountPaidForStock = NUM_SHARES * PURCHASE_PRICE
// Calculate the total amount that Joe paid, which is the amount
// he paid for the stock plus the commission he paid his broker.
Set totalPaid = amountPaidForStock + purchaseCommission
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Variables
Declare Integer cookiesEaten // Cookies eaten
Declare Integer totalCalories // Calories consumed
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Start A
Constant Integer
Display "Enter the
COOKIES_PER_BAG = 40
number of
Constant Integer
cookies eaten: "
SERVINGS_PER_BAG = 10
Constant Integer
CALORIES_PER_SERVING = 300
Input
cookiesEaten
Constant Integer
COOKIES_PER_SERVING =
COOKIES_PER_BAG /
SERVINGS_PER_BAG
Constant Integer Set totalCalories =
CALORIES_PER_COOKIE = cookiesEaten *
CALORIES_PER_SERVING / CALORIES_PER_COOKIE
COOKIES_PER_SERVING
Display "Total
Declare Integer cookiesEaten calories
Declare Integer totalCalories consumed: ",
totalCalories
A End
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
// Variables
Declare Integer male // Number of male students
Declare Integer female // Number of female students
Declare Real total // Total number of students
Declare Real percentMale // Percentage of male students
Declare Real percentFemale // Percentage of female students
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Start A
Input male
A End
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Start A
Set sugar =
cookies * SUGAR_RECIPE / Display flour, "
COOKIES_RECIPE cups of flour"
A End
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 1
Solutions
Lab 2: Modules
Note to Instructor: This lab accompanies Chapter 3 of Starting Out with Programming
Logic & Design. Material in the chapter should have been covered prior to lab
assignment. In addition, students should have had instruction on using a flowcharting
application such as Raptor and instruction on using the IDLE environment for Python.
Evaluation: The instructor should be present to answer any questions and observe the
student performing the lab. The student should turn in a hard copy (paper) or soft copy
(email) of their work. To minimize the number of attachments or individual files created
for this lab, space is set aside in the lab for students to insert completed exercises.
Directions are provided to students on copying and pasting.
Labs 2.1, 2.2, 2.3, and 2.7 use the following programming problem.
Labs 2.4 and 2.5 walk students through steps so they can become familiar with
Python code using modules and variables.
Step 2: Given the major task involved in this program, what modules might you consider
including? Describe the purpose of each module. (Reference: Defining and Calling a
Module, page 106).
Step 3: Complete the pseudocode by writing the missing lines. (Reference: Defining
and Calling a Module, page 106). Also, when writing your modules and making calls, be
sure to pass necessary variables as arguments and accept them as reference parameters if
they need to be modified in the module. (Reference: Passing Arguments by Value and by
Reference, page 127).
Module main ()
// Declare local variables
Declare Real totalSales
Declare Real countyTax
Declare Real stateTax
Declare Real totalTax
// Function calls
Call inputData(totalSales)
Call calcCounty(totalSales)
Call calcState(totalSales)
Call calcTotal(countyTax, stateTax, totalTax)
Call printData(countyTax, stateTax, totalTax)
End Module
Instructors should grade on clear variable names, proper flow of program, the correct
calculation, and the right output. Below is a sample solution to the programming
problem.
Step 7:
Main Module
calcCounty
calcState
calcTotal
printData
End
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 6
Start Start
End End
Start Start
totalTax ← countyTax +
stateTax ← totalSales * .04
stateTax
End End
printData Module
Start
End
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 7
Step 8:
# Student Name
# Date
# Description: This program tests out the different ways
# to use functions
def goodbye_message():
print('Goodbye...thank you for using my program')
Step 8:
name = inputName()
age = inputAge()
print('Hello', name)
print('Your age is', age)
# calls main
main()
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 9
Step 16:
# this function will calculate tip, tax, and the total cost
def calc_total(mealprice, tip, tax):
total = mealprice + tip + tax
return total
# this function will print tip, tax, the mealprice, and the
total
def print_info(mealprice, tip, tax, total):
print('The meal price is $', mealprice)
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 10
# calls main
main()
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 11
# this function will calculate tip, tax, and the total cost
def calcTotal(countytax, statetax):
totaltax = countytax + statetax
return totaltax
# this function will print tip, tax, the mealprice, and the total
def printData(countytax, statetax, totaltax):
print('The county tax is $', countytax)
print('The state tax is $', statetax)
print('The total tax is $', totaltax)
# calls main
main()
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 1
Lab 2: Modules
This lab accompanies Chapter 3 of Starting Out with Programming Logic & Design.
Name: ___________________________
This lab requires you to think about the steps that take place in a program by writing
algorithms. Read the following program prior to completing the lab.
A Module is a group of statements that exists within a program for the purpose of
performing a specific task.
The code for a module is known as a module definition. To execute the module, you
write a statement that calls it.
Module name()
Statement
Statement
Etc.
End Module
Calling a module is normally done from the main() module such as:
Call name()
Module main()
Real Integer number
Call inputData(number)
Call printData(number)
End Module
This lab requires you to think about the steps that take place in a program by writing
pseudocode. Read the following program prior to completing the lab.
Step 1: This program is most easily solved using just four variables. Declare the
variables that you will need in the program, using the proper data type and documenting
the purpose.
Step 2: Given the major task involved in this program, what modules might you consider
including? Describe the purpose of each module. (Reference: Defining and Calling a
Module, page 106).
Step 3: Complete the pseudocode by writing the missing lines. (Reference: Defining
and Calling a Module, page 106). Also, when writing your modules and making calls, be
sure to pass necessary variables as arguments and accept them as reference parameters if
they need to be modified in the module. (Reference: Passing Arguments by Value and by
Reference, page 127).
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 4
Module main ()
// Declare local variables
Declare Real totalSales
______________________________________________________
______________________________________________________
______________________________________________________
______________________________________________________
// Function calls
Call inputData(totalSales)
Call calcCounty(totalSales, countyTax)
______________________________________________________
______________________________________________________
______________________________________________________
End Module
Critical Review
The flowchart symbol used for a function call is a rectangle with vertical bars
on each side:
This lab requires you to think about the steps that take place in a program by designing a
flowchart. Use an application such as Raptor or Visio. Read the following program prior
to completing the lab.
Step 1: Start Raptor and save your document as Lab 2-3. The .rap file extension will be
added automatically. Start by adding a Comment box that declares your variables. Here
is a start to how your Comment box should look.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 6
Step 2: The next step in your flowchart should be to call your methods. Click the Call
Symbol on the Left and Drag and Drop to the flow lines between Start and Stop. Double
click on the Call Symbol and type the name of your first method. For example, type
inputData in the Enter Call box. Do not put the () when using Raptor. Click the Done
button. A new box will pop up that will ask you to create a new tab. Click Yes. A new
tab will be created for your new method. Notice the new Tab called inputData.
Step 3: Continue this process to add your additional methods, which are calcCounty()
calcState(), calcTotal() and printData().
Step 4: Click on the inputData tab and add the necessary code as identified in your
pseudocode in Lab 2.2. In Raptor, there is no need to pass variables as References as in
pseudocode. Your inputData method might look like the following:
Step 5: Continue to code the remaining methods, which are calcCounty() calcState(),
calcTotal() and printData(). If you happened to execute your program without
completing your program, an error will occur such as:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 7
Your calculations methods input box might look like the following:
Your output data methods box might look like the following:
Step 6: After your program is complete, click Run, then Execute to Finish. For your
input, enter 67854 as your total monthly sales. If your program is coded correctly, the
output should be as follows:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 8
Step 7: The final step is to insert your finished flowchart in the space below. Inside
Raptor, select File and the Print to Clipboard from the menu. Inside Word in the space
below, select Edit and Paste. You will have to do this for each module you created.
Critical Review
To create a function, write its definition. The keyword def is used before a
function name, followed by parentheses and a colon. Here is the general format
of a function definition in Python:
def function_name():
statement
statement
etc.
Calling a function is done in order to make the module execute. The general
format is:
function_name()
Step 1: Start the IDLE Environment for Python. Prior to entering code, save your file by
clicking on File and then Save. Select your location and save this file as Lab2-4.py. Be
sure to include the .py extension.
Step 2: Document the first few lines of your program to include your name, the date, and
a brief description of what the program does. Description of the program should be:
# This program will demonstrate various ways to
# use functions in Python.
Step 3: After your documentation, add the following function definition and function
call.
Step 4: Click Run, then Run Module to see your output. It should look like the
following:
>>> =================== RESTART =====================
>>>
Welcome to my program using functions
My name is Joe Student
>>>
Step 5: Change your program so that the function call is tabbed over, such as:
# This function is to welcome people to my program
def welcome_message():
print('Welcome to my program using functions')
print('My name is Joe Student')
Step 6: Click Run and Run Module again. You’ll notice that nothing is printed. This is
because in Python, each line in a block must be indented and aligned. Function calls
must be flushed to the left, and each line within a module must be aligned evenly. The
following will cause a syntax error.
def my_function():
print('And now for')
print('something completely')
print('different.')
Step 7: Since programs normally center around a main function, modify your program
so that it looks as follows:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 11
Critical Review
An argument is any piece of data that is passed into a function when the function
is called. A parameter is a variable that receives an argument that is passed into a
function.
A global variable can be accessed by any function within the program, but should
be avoided if at all possible.
Step 1: Start the IDLE Environment for Python. Prior to entering code, save your file
by clicking on File and then Save. Select your location and save this file as Lab2-5.py.
Be sure to include the .py extension.
Step 2: Document the first few lines of your program to include your name, the date, and
a brief description of what the program does. Description of the program should be:
Step 3: Add a function called main() and a function call to main. Your code might
look like this:
#calls main
main()
Step 4: Add a function called inputName() under the def main(): function.
Your code might look as follows:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 13
Step 5: Under your function definition, write a statement that allows the user to enter
their name. Inside of the main function, call inputName() and write a print
statement that displays the name. Your code might look as follows:
#calls main
main()
Step 6: Compile and run your program. Notice that when the program attempts to
display the name, a syntax error occurs. This is because name is declared as a local
variable within the inputName() function and main cannot access it.
Step 7: There are a couple of ways to fix this error. Examine the following code:
name = inputName()
print('Hello', name)
# calls main
main()
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 14
The local variable name is declared in main and set equal to whatever the
inputName() function returns. Notice the return name statement at the end of the
inputName() function. This passes the value that was taken in back to main.
Step 8: Add an additional function to your program that is called inputAge(). The
contents of this function should be structured similar to the inputName() function
excepts that it asks the user to enter their age. Additionally, make a call to this new
function such as age = inputAge(). You should also display the value of age after
the name is displayed. Execute your program so that it works and paste the final code
below
Step 1: Start the IDLE Environment for Python. Prior to entering code, save your file by
clicking on File and then Save. Select your location and save this file as Lab2-6.py. Be
sure to include the .py extension.
Step 2: Document the first few lines of your program to include your name, the date, and
a brief description of what the program does. Description of the program should be:
# calls main
main()
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 16
Step 5: Inside of main() under the print() # prints a blank line statement,
create a local variable named mealprice that is set to the input_meal() function.
This should look like the following:
mealprice = input_meal()
Step 6: Add the following lines of code inside of input_meal() function. This
should look like the following:
The first line asks the user to enter their meal price. The second line converts the value to
a float, since it will likely be a decimal value. This must be done with all potential
decimal values that the user enters. The third line returns the input value of mealprice
to the place where it was called (in Step 5).
Step 7: Inside of main() under the meal = input_meal() statement, create a local
variable named tip that is set to the calc_tip() function. In this case, you must
pass mealprice to the function, so it must be placed between the parentheses. This should
look like the following:
tip = calc_tip(mealprice)
def calc_tip(mealprice):
tip = mealprice * .20
return tip
The first line is the function definition. It accepts mealprice as a parameter. The
second line is to calculate tip as 20% of the mealprice. The third line returns the
calculated tip to the place where it is called.
tax = calc_tax(mealprice)
Step 10: Add the following lines of code inside of calc_tax(mealprice) function.
The entire function should look like the following:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 17
def calc_tax(mealprice):
tax = mealprice * .06
return tax
The first line is the function definition. It accepts mealprice as a parameter. The
second line is to calculate tax as 6% of the mealprice. The third line returns the
calculated tax to the place where it is called.
The first line is the function definition. It accepts mealprice, tip, and tax as
parameters. The second line is to calculate the total of all three values added together.
The third line returns the calculated total to the place where it is called.
The first line is the function definition. It accepts mealprice, tip, tax, and total
as parameters. The following lines print the mealprice, the calculated tip, the
calculated tax, and the calculated total.
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Starting Out with Programming Logic and Design 18
Step 15: Run your module and fix any errors you may have. The most common errors
may be that you have misspelled something when typing, or that your indentations are
not aligned properly. When running your program, enter 24.50 as the meal price. Your
output should look as follows:
Step 16: When your program is completed and you have tested your output in Step 15,
paste your completed program below.
Lab 2 focuses on breaking up processes into many different modules so students become
familiar with the concept of divide and conquer. Large tasks divided into many smaller
tasks will help them understand how functions and Python work together.
Naming Functions
Python requires that you follow the same rules that you follow when naming variables,
which are recapped here:
To create a function, you write its definition. Here is the general format of a function
definition in Python:
def function_name():
statement
statement
etc.
function_name()
Indentation in Python
In Python, each line in a block must be indented. Indentations that are not aligned evenly
will cause compiler errors.
A variable's scope is the part of a program in which the variable may be accessed. A
variable is visible only to statements in the variable’s scope. A local variable's scope is
the function in which the variable is created.
The following code will print that the value is 10 because the changevalue() cannot
see the local value variable.
def changevalue():
value = 50
#calls main
main()
One way to fix this issue is to pass the value to the function and set it equal to the value.
Additionally, a return value statement is added to the function. This is demonstrated in
the following code:
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Python Instructor Manual 3
def changevalue(value):
value = 50
return value
# calls main
main()
Of course, additional methods could be used to fix this problem. Another solution is to
print the value inside of the changevalue() function. However, this will not suffice
when the value needs to be passed to other functions later in the program.
Multiple arguments can also be passed to functions simply by separating the values with
commas. The arguments and the parameter list must be listed sequentially.
While there are various ways to structure programs, Lab 2 encourages students to create
local variables in main and set the function to return the modified value. For example:
# this function will calculate tip, tax, and the total cost
def calcTotal(countytax, statetax):
totaltax = countytax + statetax
SOLUTIONS MANUAL FOR STARTING OUT WITH PROGRAMMING LOGIC AND DESIGN 5TH
EDITION GADDIS
Python Instructor Manual 4
return totaltax
# this function will print tip, tax, the mealprice, and the total
def printData(countytax, statetax, totaltax):
print('The county tax is $', countytax)
print('The state tax is $', statetax)
print('The total tax is $', totaltax)
# calls main
main()