SlideShare a Scribd company logo
10
Most read
13
Most read
15
Most read
Instructor Solutions Manual (Page 3 of 212)
Answers
CHAPTER 2
EXERCISES 2.1
1. 12 2. 49 3. .125 4. 23 5. 8 6. -96 7. 2 8. 2
9. 1 10. 3 11. 1 12. 0 13. Not valid 14. Not valid
15. Valid 16. Not valid 17. Not valid 18. Not valid 19. 10
20. 14 21. 16 22. 16 23. 9 24. 8
25. print((7 * 8) + 5) 26. (1 + (2 * 9)) **3
27. print(.055 * 20) 28. 15 – (3 * (2 + (3 ** 4)))
29. print(17 * (3 + 162)) 30. (4 + (1 / 2)) – (3 + (5 / 8))
31. x y
x = 2 2 does not exist
y = 3 * x 2 6
x = y + 5 11 6
print(x + 4) 11 6
y = y + 1 11 7
32. bal inter withDr
bal = 100 100 does not exist does not exist
inter = .05 100 .05 does not exist
withDr = 25 100 .05 25
bal += (inter * bal) 105 .05 25
bal = bal - withDr 80 .05
33. 24 34. 1 8 9 35. 10 36. 225
37. 2 15 38. 5 10 39. The third line should read c = a + b.
40. 1,234 should not contain a comma; $100 should not have a dollar sign; Deposit should begin
with a lowercase letter d.
41. The first line should read interest = 0.05. 43. 10 45. 7 47. 3.128
49. -2 50. 2 51. 0 52. 1 53. 6 54. 1
55. cost += 5 56. sum *= 2 57. cost /= 6 58. sum -= 7
59. sum %= 2 60. cost //= 3
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 4 of 212)
61. revenue = 98456
costs = 45000
profit = revenue - costs
print(profit)
62. costPerShare = 25.625
numberOfShares = 400
amount = costPerShare * numberOfShares
print(amount)
63. price = 19.95
discountPercent = 30
markdown = (discountPercent / 100) * price
price -= markdown
print(round(price, 2))
64. fixedCosts = 5000
pricePerUnit = 8
costPerUnit = 6
breakEvenPoint = fixedCosts / (pricePerUnit – costPerUnit)
print(breakEvenPoint)
65. balance = 100
balance += 0.05 * balance
balance += 0.05 * balance
balance += 0.05 * balance
print(round(balance, 2))
66. balance = 100
balance = ((1.05) * balance) + 100
balance = ((1.05) * balance) + 100
balance *= 1.05
print(round(balance, 2))
67. balance = 100
balance *= 1.05 ** 10
print(round(balance, 2))
68. purchasePrice = 10
sellingPrice = 15
percentProfit = 100 * ((sellingPrice – purchasePrice) / purchasePrice)
print(percentProfit)
69. tonsPerAcre = 18
acres = 30
totalTonsProduced = tonsPerAcre * acres
print(totalTonsProduced)
70. initialVelocity = 50
initialHeight = 5
t = 3
height = (-16 * (t ** 2)) + (initialVelocity * t) + initialHeight
print(height)
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 5 of 212)
71. distance = 233
elapsedTime = 7 - 2
averageSpeed = distance / elapsedTime
print(averageSpeed)
72. miles = 23695 - 23352
gallonsUsed = 14
milesPerGallon = miles / gallonsUsed
print(milesPerGallon)
73. gallonsPerPersonDaily = 1600
numberOfPeople = 315000000
numberOfDays = 365
gallonsPerYear = gallonsPerPersonDaily * numberOfPeople * numberOfDays
print(gallonsPerYear)
74. pizzasPerSecond = 350
secondsInDay = 60 * 60 * 24
numPerDay = pizzasPerSecond * secondsInDay
print(numPerDay))
75. numberOfPizzarias = 70000
percentage = .12
numberOfRestaurants = numberOfPizzarias / percentage
print(round(numberOfRestaurants))
76. pop2000 = 281
pop2050 = 404
percentGrowth = round(100 * ((pop2050 - pop2000) / pop2000))
print(round(percentGrowth))
77. nationalDebt = 1.68e+13
population = 3.1588e+8
perCapitaDebt = nationalDebt / population
print(round(perCapitaDebt))
78. cubicFeet = (5280 ** 3)
caloriesPercubicFoot = 48600
totalNumberOfCalories = cubicFeet * caloriesPercubicFoot
print(totalNumberOfCalories))
EXERCISES 2.2
1. Python 2. Hello 3. Ernie 4. Bert 5. "o" 6. "o"
7. "h" 8. "n" 9. "Pyt" 10. [] 11. "Py" 12. "Thon"
13. "h" 14. "ytho" 15. "th" 16. "th" 17. "Python" 19. 2
20. -1 21. -1 23. 10 24. 3 25. 2 26. 5
27. -1 28. -1 29. 3 30. "BRRR" 31. 8 ball 32. 4
33. "8 BALL" 35. "hon" 37. "The Artist" 39. 5
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 6 of 212)
40. "King Lear" 41. 7 42. 6 43. 2 45. "King Kong"
46. 1 47. 12 48. 9
MUNICIPALITY Microsoft
City os
6 5
49. flute 50. Acute 51. Your age is 21. 52. Fred has 2 children.
53. A ROSE IS A ROSE IS A ROSE 54. PYTHON 55. WALLAWALLA
56. murmur 57. goodbye 58. eighth 59. Mmmmmmm.
60. ***YES*** 61. a b 62. spamspamspamspam
63. 76 trombones 64. 5.5 65. 17 66. 8 67. 8 68. 8
69. The Great 9 70. The Dynamic Duo 71. s[:-1] 72. s[2:]
73. -8 74. 7 75. True 76. True 77. True 78. True
79. 234-5678 should be surrounded with quotation marks.
80. I came to Casablanca for the waters. should be surrounded by quotation marks.
81. for is a reserved word and cannot be used as a variable name.
82. A string cannot be concatenated with a number. The second line should be written
print("Age: " + str(age))
83. The string should be replaced with "Say it ain't so."
84. Should be written print('George "Babe" Ruth')
85. Upper should be changed to upper.
86. lower should be changed to lower()
87. A string cannot be concatenated with a number.
88. The characters in a number cannot be indexed.
89. find is a not an allowable method for a number; only for a string.
90. The len function can not be applied to numbers.
91. The string "Python" does not have a character of index 8.
92. show[9]is not valid since the string "Spamalot" does not have a character of index 9.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 7 of 212)
93. ## Display an inventor's name and year of birth.
firstName = "Thomas"
middleName = "Alva"
lastName = "Edison"
yearOfBirth = 1847
print(firstName, middleName, lastName + ',', yearOfBirth)
94. item = "ketchup"
regularPrice = 1.8
discount = 0.27
print(regularPrice - discount) + " is the sale price of " + item + "."
95. ## Display a copyright statement.
publisher = "Pearson"
print("(c)", publisher)
96. prefix = "Fore"
print(prefix + "warned is " + prefix + "armed.")
97. ## Calculate the distance from a storm.
prompt = "Enter number of seconds between lightning and thunder: "
numberOfSeconds = float(input(prompt))
distance = numberOfSeconds / 5
distance = round(distance, 2)
print("Distance from storm:", distance, "miles.")
98. ## Calculate training heart rate.
age = float(input("Enter your age: "))
rhr = int(input("Enter your resting heart rate: "))
thr = .7 * (220 - age) + (.3 * rhr)
print("Training heart rate:", round(thr), "beats/minute.")
99. ## Calculate weight loss during a triathlon.
cycling = float(input("Enter number of hours cycling: "))
running = float(input("Enter number of hours running: "))
swimming = float(input("Enter number of hours swimming: "))
pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500
pounds =round(pounds, 1)
print("Weight loss:", pounds, "pounds")
Enter number of hours cycling: 2
Enter number of hours running: 3
Enter number of hours swimming: 1
Weight loss: 0.6 pounds
Enter number of seconds between lightning and thunder: 1.25
Distance from storm: 0.25 miles.
Enter your age: 20
Enter your resting heart rate: 70
Training heart rate: 161 beats/min.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 8 of 212)
100. ## Calculate cost of electricity.
wattage = int(input("Enter wattage: "))
hoursUsed = float(input("Enter number of hours used: "))
price = float(input("Enter price per kWh in cents: "))
cost = (wattage * hoursUsed) / (1000 * price)
print("Cost of electricity:", '$' + str(round(cost, 2)))
101. ## Calculate percentage of games won by a baseball team.
name = input("Enter name of team: ")
gamesWon = int(input("Enter number of games won: "))
gamesList = int(input("Enter number of games lost: "))
percentageWon = round(100 * (gamesWon) / (gamesWon + gamesList), 1)
print(name, "won", str(percentageWon) + '%', "of their games.")
102. ## Calculate price/earnings ratio.
earningsPerShare = float(input("Enter earnings per share: "))
pricePerShare = float(input("Enter price per share: "))
PEratio = pricePerShare / earningsPerShare
print("Price-to-Earnings ratio:", PEratio)
103. ## Determine the speed of a skidding car.
distance = float(input("Enter distance skidded (in feet): "))
speed = (24 * distance) ** .5
speed = round(speed, 2)
print("Estimated speed:", speed, "miles per hour")
104. ## Convert a percent to a decimal.
percentage = input("Enter percentage: ")
percent = float(percentage[:-1]) / 100
print("Equivalent decimal:", percent)
Enter name of team: Yankees
Enter number of games won: 68
Enter number of games lost: 52
Yankees won 56.7% of their games.
Enter distance skidded: 54
Estimated speed: 36.0 miles per hour
Enter wattage: 100
Enter number of hours used: 720
Enter price per kWh in cents: 11.76
Cost of electricity: $6.12
Enter earnings per share: 5.25
Enter price per share: 68.25
Price-to-Earnings ratio: 13.0
Enter percentage: 125%
Equivalent decimal: 1.25
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 9 of 212)
105. ## Convert speed from kph to mph.
speedInKPH = float(input("Enter speed in KPH: "))
speedInMPH = speedInKPH * .6214
print("Speed in MPH:", round(speedInMPH, 2))
Note: The world’s fastest animal, the cheetah, can run at the speed of 112.6541 kilometers
per hour.
106. ## Server's tip.
bill = float(input("Enter amount of bill: "))
percentage = float(input("Enter percentage tip: "))
tip = (bill * percentage) / 100
print("Tip:", '$' + str(round(tip, 2)))
107. ## Calculate equivalent CD interest rate for municipal bond rate.
taxBracket = float(input("Enter tax bracket (as decimal): "))
bondRate = float(input("Enter municipal bond interest rate (as %): "))
equivCDrate = bondRate / (1 - taxBracket)
print("Equivalent CD interest rate:", str(round(equivCDrate, 3)) + '%')
108. ## Marketing terms.
purchasePrice = float(input("Enter purchase price: "))
sellingPrice = float(input("Enter selling price: "))
markup = sellingPrice - purchasePrice
percentageMarkup = 100 * (markup / purchasePrice)
profitMargin = 100 * (markup / sellingPrice)
print("Markup:", '$' + str(round(markup, 2)))
print("Percentage markup:", str(round(percentageMarkup, 2)) + '%')
print("Profit margin:", str(round(profitMargin, 2)) + '%')
109. ## Analyze a number.
number = input("Enter number: ")
decimalPoint = number.find('.')
print(decimalPoint, "digits to left of decimal point")
print(len(number) - decimalPoint - 1, "digits to right of decimal point")
Enter speed in KPH: 112.6541
Speed in MPH: 70.00
Enter tax bracket (as decimal): .37
Enter municipal bond interest rate (as %): 3.26
Equivalent CD interest rate: 5.175%
Enter number: 76.543
2 digits to left of decimal point
3 digits to right of decimal point
Enter amount of bill: 21.50
Enter percentage tip: 18
Tip: $3.87
Enter purchase price: 215
Enter selling price: 645
Markup: $430.0
Percentage markup: 200.0%
Profit margin: 66.67%
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 10 of 212)
110. ## Word replacement.
sentence = input("Enter a sentence: ")
word1 = input("Enter word to replace: ")
word2 = input("Enter replacement word: ")
location = sentence.find(word1)
newSentence = sentence[:location] + word2 + sentence[location + len(word1):]
print(newSentence)
111. ## Convert a number of months to years and months.
numberOfMonths = int(input("Enter number of months: "))
years = numberOfMonths // 12
months = numberOfMonths % 12
print(numberOfMonths, "months is", years, "years and", months, "months.")
112. ## Convert lengths.
numberOfInches = int(input("Enter number of inches: "))
feet = numberOfInches // 12
inches = numberOfInches % 12
print(numberOfInches, "inches equals", feet, "feet and", inches, "inches.")
EXERCISES 2.3
1. Bon Voyage! 2. Price: $23.45 3. Portion: 90% 4. Python
5. 1 x 2 x 3 6. tic-tac-toe 7. father-in-law 8. father-in-law
9. T-shirt 10. spam and eggs 11. Python 12. on-site repair
13. Hello 14. Hello 15. One Two Three Four
World!
World!
16. 1 2 3 17. NUMBER SQUARE 18. COUNTRY LAND AREA
Detroit Lions 2 4 India 2.5 million sq km
Indianapolis Colts 3 9 China 9.6 million sq km
19. Hello World! 20. STATE CAPITAL 21. 01234567890
Hello World! North Dakota Bismarck A B C
South Dakota Pierre
Enter a sentence: Live long and prosper.
Enter word to replace: prosper
Enter replacement word: proper
Live long and proper.
Enter number of months: 234
234 months is 19 years and 6
months.
Enter number of inches: 185
185 inches is 15 feet and 5 inches.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 11 of 212)
22. 0123456789012345 23. 01234567890123456 24. 01234567890
one two three one two three A B C
25. 0123456789 26. 0123456789
12.30% 1,234
123.0% 1,234
1,230.00% 1,234
27. $1,234.57 28. 1,234 29. 1 30. #1,234.00
31. Language Native speakers % of World Pop.
Mandarin 935,000,000 14.10%
Spanish 387,000,000 5.85%
English 365,000,000 5.52%
32. Major Percent of Students
Biology 6.2%
Psychology 5.4%
Nursing 4.7%
33. Be yourself – everyone else is taken.
34. Plan first, code later
35. Always look on the bright side of life.
36. And now for something completely different.
37. The product of 3 and 4 is 12.
38. The chances of winning the Powerball Lottery are 1 in 175,223,510.
39. The square root of 2 is about 1.4142.
40. Pi is approximately 3.14159.
41. In a randomly selected group of 23 people, the probability
is 0.51 that 2 people have the same birthday.
42. The cost of Alaska was about $10.86 per square mile.
43. You miss 100% of the shots you never take. - Wayne Gretsky
44. 12% of the members of the U.S. Senate are from New England.
45. 22.28% of the UN nations are in Europe.
46. The area of Alaska is 17.5% of the area of the U.S.
47. abracadabra
48. When you have nothing to say, say nothing.
49. Be kind whenever possible. It is always possible. - Dalai Lama
50. If you can dream it, you can do it. - Walt Disney
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 12 of 212)
51. Yes 52. Yes
53. ## Calculate a server's tip.
bill = float(input("Enter amount of bill: "))
percentage = float(input("Enter percentage tip: "))
tip = (bill * percentage) / 100
print("Tip: ${0:.2f}".format(tip))
54. ## Calculate income.
revenue = eval(input("Enter revenue: "))
expenses = eval(input("Enter expenses: "))
netIncome = revenue - expenses
print("Net income: ${0:,.2f}".format(netIncome))
55. ## Calculate a new salary.
beginningSalary = float(input("Enter beginning salary: "))
raisedSalary = 1.1 * beginningSalary
cutSalary = .9 * raisedSalary
percentChange = (cutSalary - beginningSalary) / beginningSalary
print("New salary: ${0:,.2f}".format(cutSalary))
print("Change: {0:.2%}".format(percentChange))
56. ## Calculte a change in salary.
beginningSalary = float(input("Enter beginning salary: "))
raisedSalary = 1.05 * 1.05 * 1.05 * beginningSalary
percentChange = (raisedSalary - beginningSalary) / beginningSalary
print("New salary: ${0:,.2f}".format(raisedSalary))
print("Change: {0:.2%}".format(percentChange))
57. ## Calculate a future value.
p = float(input("Enter principal: "))
r = float(input("Enter interest rate (as %): "))
n = int(input("Enter number of years: "))
futureValue = p * (1 + (r / 100)) ** n
print("Future value: ${0:,.2f}".format(futureValue))
Enter amount of bill: 45.50
Enter percentage tip: 20
Tip: $9.10
Enter beginning salary: 42500
New salary: $42,075.00
Change: -1.00%
Enter principal: 2500
Enter interest rate (as %): 3.5
Enter number of years: 2
Future value: $2,678.06
Enter beginning salary: 35000
New salary: $40,516.88
Change: 15.76%
Enter revenue: 550000
Enter expenses: 410000
Net income: $140,000.00
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 13 of 212)
58. ## Calculate a present value.
f = float(input("Enter future value: "))
r = float(input("Enter interest rate (as %): "))
n = int(input("Enter number of years: "))
presentValue = f / ((1 + (r / 100)) ** n)
print("Present value: ${0:,.2f}".format(presentValue))
EXERCISES 2.4
1. Pennsylvania Hawaii 2. New Jersey, Arizona 3. Alaska Hawaii
4. 50 5. Delaware Delaware 6. 0 7. 48 8. 22
9. Ohio 10. Hawaii Hawaii 11. DELAWARE 12. Puerto Rico
13. ['Puerto Rico'] 14. Georgia 15. United States 16. 48
17. ['New Jersey', 'Georgia', 'Connecticut']
18. ['Pennsylvania', 'New Jersey', 'Georgia']
19. ['Oklahoma', 'New Mexico', 'Arizona']
20. ['New Mexico', 'Arizona', 'Alaska']
21. ['Delaware', 'Pennsylvania', 'New Jersey', 'Georgia']
22. ['Delaware'] 23. ['Arizona', 'Alaska', 'Hawaii']
24. ['Alaska', 'Hawaii'] 25. [] 26. [] 27. Georgia
28. Arizona 29. ['Alaska', 'Hawaii'] 30. Massachusetts
31. New Mexico 32. New Jersey 33. 10 34. 30 35. 0 36. 50
37. 48 38. 46 39. ['Hawaii', 'Puerto Rico', 'Guam']
40. ['Alaska', 'Hawaii', ['Puerto Rico', 'Guam']]
41. ['Hawaii', 'Puerto Rico', 'Guam']
42. ['Arizona', "Seward's Folly", 'Hawaii']
43. ['Delaware', 'Commonwealth of Pennsylvania', 'New Jersey']
44. ['Delaware', 'Commonwealth of Pennsylvania', 'Pennsylvania']
45. ['New', 'Mexico'] 46. ['Jersey', 'New', 'Mexico']
['New', 'Jersey']
Enter future value: 10000
Enter interest rate (as %): 4
Enter number of years: 6
Present value: $7,903.15
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 14 of 212)
47. Pennsylvania,New Jersey,Georgia 48. ['Jersey', 'New', 'Mexico']
49. 8 50. 8 51. 100 52. 7 53. 0 54. 98
55. Largest Number: 8 56. Smallest Number: 0 57. Total: 16
58. Average 4.0
59. This sentence contains five words.
This sentence contains six different words.
60. ['all', 'for', 'one'] 61. Babbage, Charles 62. Guido Rossum
63. Middle Name: van 64. Python 65. When in the course of human events
66. Less is more. 67. editor-in-chief 68. merry-go-round
69. e**pluribus**unum 70. ['around', 'the', 'clock']
71. ['New York', 'NY', 'Empire State', 'Albany']
72. ['France', 'England', 'Spain'] 73. ['France', 'England', 'Spain']
74. a bcd 75. programmer
76. Live let live. 77. Follow your own star.
78. Largest Number: 8
Length: 4
Total: 16
Number list: [6, 2, 8, 0]
79. 987-654-3219 80. Dairy 81. [3, 9, 6] 82. (-5, 17, 123)
83. each 84. (0, 2, 3) 85. ['soprano', 'tenor', 'alto', 'bass']
86. ['soprano', 'tenor', 'alto', 'bass'] 87. ['gold', 'silver', 'bronze']
88. ['gold', 'silver', 'bronze'] 89. murmur
90. [0, 0, 0, 0] 91. ('Happy', 'Sneezy', 'Bashful')
92. ['Nina', 'Pinta'] 93. 1 94. 2
95. Index out of range. The list does not have an item of index 3.
96. The statement word[1] = 'p' is not valid since strings are immutable.
97. The join method only can be applied to a list consisting entirely of strings.
98. The tuple does not have an item of index 4.
99. The second line is not valid. Items in a tuple cannot be reassigned values directly.
100. Tuples do not support the append method.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 15 of 212)
101. ## Count the number of words in a sentence.
sentence = input("Enter a sentence: ")
L = sentence.split(" ")
print("Number of words:", len(L))
102. ## Analyze a sentence
sentence = input("Enter a sentence: ")
L = sentence.split()
print("First word:", L[0])
print("Last word:", L[-1][:-1])
103. ## Display a name.
name = input("Enter a 2-part name: ")
L = name.split()
print("{0:s}, {1:s}".format(L[1], L[0]))
104. ## Extract the middle name from a three-part name.
name = input("Enter a 3-part Name: ")
L = name.split()
print("Middle Name:", L[1])
PROGRAMMING PROJECTS CHAPTER 2
1. ## Make change for an amount of less than one dollar.
amount = int(input("Enter amount of change: "))
remainder = amount
quarters = remainder // 25
remainder %= 25
dimes = remainder // 10
remainder %= 10
nickels = remainder // 5
remainder %= 5
cents = remainder
print("Quarters:", quarters, end=" ")
print("tDimes:", dimes)
print("Nickels:", nickels, end=" ")
print("tCents:", cents)
Enter a sentence: This sentence contains five words.
Number of words: 5
Enter a 2-part name: Charles Babbage
Revised form: Babbage, Charles
Enter amount of change: 93
Quarters: 3 Dimes: 1
Nickels: 1 Cents: 3
Enter a 3-part name: Augusta Ada Byron
Middle name: Ada
Enter a sentence: Reach for the stars.
First word: Reach
Last word: stars
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 16 of 212)
2. ## Determine the monthly payment for a car loan.
loanAmount = float(input("Enter amount of loan: "))
interestRate = float(input("Enter interest rate (%): "))
numYears = float(input("Enter number of years: "))
i = interestRate / 1200
monthlyPayment = (i / (1 - ((1 + i) ** (-12 * numYears)))) * loanAmount
print("Monthly payment: ${0:,.2f}".format(monthlyPayment))
3. faceValue = float(input("Enter face value of bond: "))
couponRate = float(input("Enter coupon interest rate: "))
interest = faceValue * couponRate
marketPrice = float(input("Enter current market price: "))
yrsUntilMaturity = float(input("Enter years until maturity: "))
a = (faceValue - marketPrice) / yrsUntilMaturity
b = (faceValue + marketPrice) / 2
ytm = (interest + a) / b
print("Approximate YTM: {0:.2%}".format(ytm))
4. ## Determine the unit price of a purchase.
price = float(input("Enter price of item: "))
print("Enter weight of item in pounds and ounces separately.")
pounds = float(input("Enter pounds: "))
ounces = float(input("Enter ounces: "))
weightInOunces = 16 * pounds + ounces
pricePerOunce = price / weightInOunces
print("Price per ounce: ${0:.2f}".format(pricePerOunce))
5. ## Describe the distribution in a stock portfolio.
spy = float(input("Enter amount invested in SPY: "))
qqq = float(input("Enter amount invested in QQQ: "))
eem = float(input("Enter amount invested in EEM: "))
vxx = float(input("Enter amount invested in VXX: "))
total = spy + qqq + eem + vxx
print()
print("{0:6s}{1:>12s}".format("ETF", "PERCENTAGE"))
print("-" * 18)
Enter amount of loan: 12000
Enter interest rate (%): 6.4
Enter number of years: 5
Monthly payment: $234.23
Enter face value of bond: 1000
Enter coupon interest rate: .04
Enter current market price: 1180
Enter years until maturity: 15
Approximate YTM: 2.57%
Enter price of item: 25.50
Enter weight of item in pounds and ounces separately.
Enter pounds: 1
Enter ounces: 9
Price per ounce: $1.02
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Instructor Solutions Manual (Page 17 of 212)
print("{0:6s}{1:10.2%}".format("SPY", spy / total))
print("{0:6s}{1:10.2%}".format("QQQ", qqq / total))
print("{0:6s}{1:10.2%}".format("EEM", eem / total))
print("{0:6s}{1:10.2%}".format("VXX", vxx / total))
print()
print("{0:s}: ${1:,.2f}".format("TOTAL AMOUNT INVESTED", total))
6. ## Convert a measurement from miles, yards, feet,
## and inches, to a metric one in meters, kilometers,
## and centimeters.
miles = float(input("Enter number of miles: "))
yards = float(input("Enter number of yards: "))
feet = float(input("Enter number of feet: "))
inches = float(input("Enter number of inches: "))
# Step #1: Add up given measurements into inches
totalInches = inches + 12 * feet + 36 * yards + 63360 * miles
# Step #2: Convert total inches into total meters
totalMeters = totalInches / 39.3700787
# Step #3: Compute kilometers, whole meters, and centimeters
# Step 3a: compute # of kilometers, subtract from meters
kilometers = int(totalMeters / 1000)
totalMeters = totalMeters - 1000 * kilometers
meters = int(totalMeters)
centimeters = 100 * (totalMeters - meters)
centimeters = round(centimeters, 1)
print("Metric length:")
print(" ", kilometers, "kilometers")
print(" ", meters, "meters")
print(" ", centimeters, "centimeters")
Enter amount invested in SPY: 876543.21
Enter amount invested in QQQ: 234567.89
Enter amount invested in EEM: 345678.90
Enter amount invested in VXX: 123456.78
ETF PERCENTAGE
------------------
SPY 55.47%
QQQ 14.84%
EEM 21.87%
VXX 7.81%
TOTAL AMOUNT INVESTED: $1,580,246.78
Enter number of miles: 5
Enter number of yards: 20
Enter number of feet: 2
Enter number of inches: 4
Metric length:
8 kilometers
65 meters
73.5 centimeters
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

More Related Content

PPTX
Microsoft company
PPTX
Dell case study (management)
PDF
Coding for kids
PPT
Introduction to Scratch Programming
PPTX
MGT 201 Historical Foundations Of Management
PPTX
A case based presentation on Microsoft Company
PDF
Dell - Strategy Analysis
PPTX
Introduction to Coding
Microsoft company
Dell case study (management)
Coding for kids
Introduction to Scratch Programming
MGT 201 Historical Foundations Of Management
A case based presentation on Microsoft Company
Dell - Strategy Analysis
Introduction to Coding

What's hot (20)

DOC
C fundamental
PDF
Chapter 1 : Balagurusamy_ Programming ANsI in C
PPTX
Lesson 7 io statements
DOCX
Practical write a c program to reverse a given number
PDF
Cn os-lp lab manual k.roshan
PPT
Preprocessors
PPTX
Single Linked List - Insert .pptx
PPTX
Introduction to C Programming
PPSX
Stacks Implementation and Examples
PPTX
Application of Stack - Yadraj Meena
PDF
Preprocessor
PPT
Recursion in c
PDF
Parsing Expression With Xtext
PPTX
POINTERS IN C
PDF
Chapter 6 Balagurusamy Programming ANSI in c
DOCX
Bucles compuestos ejercicios en código java
PDF
Chapter 3 : Balagurusamy Programming ANSI in C
PPT
Java: Java Applets
PPSX
DOC
Arrays and Strings
C fundamental
Chapter 1 : Balagurusamy_ Programming ANsI in C
Lesson 7 io statements
Practical write a c program to reverse a given number
Cn os-lp lab manual k.roshan
Preprocessors
Single Linked List - Insert .pptx
Introduction to C Programming
Stacks Implementation and Examples
Application of Stack - Yadraj Meena
Preprocessor
Recursion in c
Parsing Expression With Xtext
POINTERS IN C
Chapter 6 Balagurusamy Programming ANSI in c
Bucles compuestos ejercicios en código java
Chapter 3 : Balagurusamy Programming ANSI in C
Java: Java Applets
Arrays and Strings
Ad

Similar to Solution Manual for Introduction to Programming Using Python 1st Edition by Schneider (20)

PPTX
r studio presentation.pptx
PPTX
r studio presentation.pptx
PDF
Regression and Classification with R
PDF
8 arrays and pointers
PDF
PDF
JavaOne2010 Groovy/Spring Roo
PDF
MH prediction modeling and validation in r (2) classification 190709
PDF
"Solutions for Exercises" in Starting Out with Python 4th Global Edition by T...
PDF
Python From Scratch (1).pdf
PPT
array
PDF
4 operators, expressions & statements
PDF
DOCX
Let us C (by yashvant Kanetkar) chapter 3 Solution
PDF
PPTX
R programming language
KEY
Haskellで学ぶ関数型言語
PDF
The Ring programming language version 1.8 book - Part 66 of 202
r studio presentation.pptx
r studio presentation.pptx
Regression and Classification with R
8 arrays and pointers
JavaOne2010 Groovy/Spring Roo
MH prediction modeling and validation in r (2) classification 190709
"Solutions for Exercises" in Starting Out with Python 4th Global Edition by T...
Python From Scratch (1).pdf
array
4 operators, expressions & statements
Let us C (by yashvant Kanetkar) chapter 3 Solution
R programming language
Haskellで学ぶ関数型言語
The Ring programming language version 1.8 book - Part 66 of 202
Ad

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
KodekX | Application Modernization Development
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Cloud computing and distributed systems.
PDF
Electronic commerce courselecture one. Pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25 Week I
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
sap open course for s4hana steps from ECC to s4
Unlocking AI with Model Context Protocol (MCP)
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Big Data Technologies - Introduction.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
The AUB Centre for AI in Media Proposal.docx
MIND Revenue Release Quarter 2 2025 Press Release
KodekX | Application Modernization Development
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Cloud computing and distributed systems.
Electronic commerce courselecture one. Pdf
Network Security Unit 5.pdf for BCA BBA.

Solution Manual for Introduction to Programming Using Python 1st Edition by Schneider

  • 1. Instructor Solutions Manual (Page 3 of 212) Answers CHAPTER 2 EXERCISES 2.1 1. 12 2. 49 3. .125 4. 23 5. 8 6. -96 7. 2 8. 2 9. 1 10. 3 11. 1 12. 0 13. Not valid 14. Not valid 15. Valid 16. Not valid 17. Not valid 18. Not valid 19. 10 20. 14 21. 16 22. 16 23. 9 24. 8 25. print((7 * 8) + 5) 26. (1 + (2 * 9)) **3 27. print(.055 * 20) 28. 15 – (3 * (2 + (3 ** 4))) 29. print(17 * (3 + 162)) 30. (4 + (1 / 2)) – (3 + (5 / 8)) 31. x y x = 2 2 does not exist y = 3 * x 2 6 x = y + 5 11 6 print(x + 4) 11 6 y = y + 1 11 7 32. bal inter withDr bal = 100 100 does not exist does not exist inter = .05 100 .05 does not exist withDr = 25 100 .05 25 bal += (inter * bal) 105 .05 25 bal = bal - withDr 80 .05 33. 24 34. 1 8 9 35. 10 36. 225 37. 2 15 38. 5 10 39. The third line should read c = a + b. 40. 1,234 should not contain a comma; $100 should not have a dollar sign; Deposit should begin with a lowercase letter d. 41. The first line should read interest = 0.05. 43. 10 45. 7 47. 3.128 49. -2 50. 2 51. 0 52. 1 53. 6 54. 1 55. cost += 5 56. sum *= 2 57. cost /= 6 58. sum -= 7 59. sum %= 2 60. cost //= 3 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 2. Instructor Solutions Manual (Page 4 of 212) 61. revenue = 98456 costs = 45000 profit = revenue - costs print(profit) 62. costPerShare = 25.625 numberOfShares = 400 amount = costPerShare * numberOfShares print(amount) 63. price = 19.95 discountPercent = 30 markdown = (discountPercent / 100) * price price -= markdown print(round(price, 2)) 64. fixedCosts = 5000 pricePerUnit = 8 costPerUnit = 6 breakEvenPoint = fixedCosts / (pricePerUnit – costPerUnit) print(breakEvenPoint) 65. balance = 100 balance += 0.05 * balance balance += 0.05 * balance balance += 0.05 * balance print(round(balance, 2)) 66. balance = 100 balance = ((1.05) * balance) + 100 balance = ((1.05) * balance) + 100 balance *= 1.05 print(round(balance, 2)) 67. balance = 100 balance *= 1.05 ** 10 print(round(balance, 2)) 68. purchasePrice = 10 sellingPrice = 15 percentProfit = 100 * ((sellingPrice – purchasePrice) / purchasePrice) print(percentProfit) 69. tonsPerAcre = 18 acres = 30 totalTonsProduced = tonsPerAcre * acres print(totalTonsProduced) 70. initialVelocity = 50 initialHeight = 5 t = 3 height = (-16 * (t ** 2)) + (initialVelocity * t) + initialHeight print(height) © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 3. Instructor Solutions Manual (Page 5 of 212) 71. distance = 233 elapsedTime = 7 - 2 averageSpeed = distance / elapsedTime print(averageSpeed) 72. miles = 23695 - 23352 gallonsUsed = 14 milesPerGallon = miles / gallonsUsed print(milesPerGallon) 73. gallonsPerPersonDaily = 1600 numberOfPeople = 315000000 numberOfDays = 365 gallonsPerYear = gallonsPerPersonDaily * numberOfPeople * numberOfDays print(gallonsPerYear) 74. pizzasPerSecond = 350 secondsInDay = 60 * 60 * 24 numPerDay = pizzasPerSecond * secondsInDay print(numPerDay)) 75. numberOfPizzarias = 70000 percentage = .12 numberOfRestaurants = numberOfPizzarias / percentage print(round(numberOfRestaurants)) 76. pop2000 = 281 pop2050 = 404 percentGrowth = round(100 * ((pop2050 - pop2000) / pop2000)) print(round(percentGrowth)) 77. nationalDebt = 1.68e+13 population = 3.1588e+8 perCapitaDebt = nationalDebt / population print(round(perCapitaDebt)) 78. cubicFeet = (5280 ** 3) caloriesPercubicFoot = 48600 totalNumberOfCalories = cubicFeet * caloriesPercubicFoot print(totalNumberOfCalories)) EXERCISES 2.2 1. Python 2. Hello 3. Ernie 4. Bert 5. "o" 6. "o" 7. "h" 8. "n" 9. "Pyt" 10. [] 11. "Py" 12. "Thon" 13. "h" 14. "ytho" 15. "th" 16. "th" 17. "Python" 19. 2 20. -1 21. -1 23. 10 24. 3 25. 2 26. 5 27. -1 28. -1 29. 3 30. "BRRR" 31. 8 ball 32. 4 33. "8 BALL" 35. "hon" 37. "The Artist" 39. 5 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 4. Instructor Solutions Manual (Page 6 of 212) 40. "King Lear" 41. 7 42. 6 43. 2 45. "King Kong" 46. 1 47. 12 48. 9 MUNICIPALITY Microsoft City os 6 5 49. flute 50. Acute 51. Your age is 21. 52. Fred has 2 children. 53. A ROSE IS A ROSE IS A ROSE 54. PYTHON 55. WALLAWALLA 56. murmur 57. goodbye 58. eighth 59. Mmmmmmm. 60. ***YES*** 61. a b 62. spamspamspamspam 63. 76 trombones 64. 5.5 65. 17 66. 8 67. 8 68. 8 69. The Great 9 70. The Dynamic Duo 71. s[:-1] 72. s[2:] 73. -8 74. 7 75. True 76. True 77. True 78. True 79. 234-5678 should be surrounded with quotation marks. 80. I came to Casablanca for the waters. should be surrounded by quotation marks. 81. for is a reserved word and cannot be used as a variable name. 82. A string cannot be concatenated with a number. The second line should be written print("Age: " + str(age)) 83. The string should be replaced with "Say it ain't so." 84. Should be written print('George "Babe" Ruth') 85. Upper should be changed to upper. 86. lower should be changed to lower() 87. A string cannot be concatenated with a number. 88. The characters in a number cannot be indexed. 89. find is a not an allowable method for a number; only for a string. 90. The len function can not be applied to numbers. 91. The string "Python" does not have a character of index 8. 92. show[9]is not valid since the string "Spamalot" does not have a character of index 9. © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 5. Instructor Solutions Manual (Page 7 of 212) 93. ## Display an inventor's name and year of birth. firstName = "Thomas" middleName = "Alva" lastName = "Edison" yearOfBirth = 1847 print(firstName, middleName, lastName + ',', yearOfBirth) 94. item = "ketchup" regularPrice = 1.8 discount = 0.27 print(regularPrice - discount) + " is the sale price of " + item + "." 95. ## Display a copyright statement. publisher = "Pearson" print("(c)", publisher) 96. prefix = "Fore" print(prefix + "warned is " + prefix + "armed.") 97. ## Calculate the distance from a storm. prompt = "Enter number of seconds between lightning and thunder: " numberOfSeconds = float(input(prompt)) distance = numberOfSeconds / 5 distance = round(distance, 2) print("Distance from storm:", distance, "miles.") 98. ## Calculate training heart rate. age = float(input("Enter your age: ")) rhr = int(input("Enter your resting heart rate: ")) thr = .7 * (220 - age) + (.3 * rhr) print("Training heart rate:", round(thr), "beats/minute.") 99. ## Calculate weight loss during a triathlon. cycling = float(input("Enter number of hours cycling: ")) running = float(input("Enter number of hours running: ")) swimming = float(input("Enter number of hours swimming: ")) pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500 pounds =round(pounds, 1) print("Weight loss:", pounds, "pounds") Enter number of hours cycling: 2 Enter number of hours running: 3 Enter number of hours swimming: 1 Weight loss: 0.6 pounds Enter number of seconds between lightning and thunder: 1.25 Distance from storm: 0.25 miles. Enter your age: 20 Enter your resting heart rate: 70 Training heart rate: 161 beats/min. © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 6. Instructor Solutions Manual (Page 8 of 212) 100. ## Calculate cost of electricity. wattage = int(input("Enter wattage: ")) hoursUsed = float(input("Enter number of hours used: ")) price = float(input("Enter price per kWh in cents: ")) cost = (wattage * hoursUsed) / (1000 * price) print("Cost of electricity:", '$' + str(round(cost, 2))) 101. ## Calculate percentage of games won by a baseball team. name = input("Enter name of team: ") gamesWon = int(input("Enter number of games won: ")) gamesList = int(input("Enter number of games lost: ")) percentageWon = round(100 * (gamesWon) / (gamesWon + gamesList), 1) print(name, "won", str(percentageWon) + '%', "of their games.") 102. ## Calculate price/earnings ratio. earningsPerShare = float(input("Enter earnings per share: ")) pricePerShare = float(input("Enter price per share: ")) PEratio = pricePerShare / earningsPerShare print("Price-to-Earnings ratio:", PEratio) 103. ## Determine the speed of a skidding car. distance = float(input("Enter distance skidded (in feet): ")) speed = (24 * distance) ** .5 speed = round(speed, 2) print("Estimated speed:", speed, "miles per hour") 104. ## Convert a percent to a decimal. percentage = input("Enter percentage: ") percent = float(percentage[:-1]) / 100 print("Equivalent decimal:", percent) Enter name of team: Yankees Enter number of games won: 68 Enter number of games lost: 52 Yankees won 56.7% of their games. Enter distance skidded: 54 Estimated speed: 36.0 miles per hour Enter wattage: 100 Enter number of hours used: 720 Enter price per kWh in cents: 11.76 Cost of electricity: $6.12 Enter earnings per share: 5.25 Enter price per share: 68.25 Price-to-Earnings ratio: 13.0 Enter percentage: 125% Equivalent decimal: 1.25 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 7. Instructor Solutions Manual (Page 9 of 212) 105. ## Convert speed from kph to mph. speedInKPH = float(input("Enter speed in KPH: ")) speedInMPH = speedInKPH * .6214 print("Speed in MPH:", round(speedInMPH, 2)) Note: The world’s fastest animal, the cheetah, can run at the speed of 112.6541 kilometers per hour. 106. ## Server's tip. bill = float(input("Enter amount of bill: ")) percentage = float(input("Enter percentage tip: ")) tip = (bill * percentage) / 100 print("Tip:", '$' + str(round(tip, 2))) 107. ## Calculate equivalent CD interest rate for municipal bond rate. taxBracket = float(input("Enter tax bracket (as decimal): ")) bondRate = float(input("Enter municipal bond interest rate (as %): ")) equivCDrate = bondRate / (1 - taxBracket) print("Equivalent CD interest rate:", str(round(equivCDrate, 3)) + '%') 108. ## Marketing terms. purchasePrice = float(input("Enter purchase price: ")) sellingPrice = float(input("Enter selling price: ")) markup = sellingPrice - purchasePrice percentageMarkup = 100 * (markup / purchasePrice) profitMargin = 100 * (markup / sellingPrice) print("Markup:", '$' + str(round(markup, 2))) print("Percentage markup:", str(round(percentageMarkup, 2)) + '%') print("Profit margin:", str(round(profitMargin, 2)) + '%') 109. ## Analyze a number. number = input("Enter number: ") decimalPoint = number.find('.') print(decimalPoint, "digits to left of decimal point") print(len(number) - decimalPoint - 1, "digits to right of decimal point") Enter speed in KPH: 112.6541 Speed in MPH: 70.00 Enter tax bracket (as decimal): .37 Enter municipal bond interest rate (as %): 3.26 Equivalent CD interest rate: 5.175% Enter number: 76.543 2 digits to left of decimal point 3 digits to right of decimal point Enter amount of bill: 21.50 Enter percentage tip: 18 Tip: $3.87 Enter purchase price: 215 Enter selling price: 645 Markup: $430.0 Percentage markup: 200.0% Profit margin: 66.67% © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 8. Instructor Solutions Manual (Page 10 of 212) 110. ## Word replacement. sentence = input("Enter a sentence: ") word1 = input("Enter word to replace: ") word2 = input("Enter replacement word: ") location = sentence.find(word1) newSentence = sentence[:location] + word2 + sentence[location + len(word1):] print(newSentence) 111. ## Convert a number of months to years and months. numberOfMonths = int(input("Enter number of months: ")) years = numberOfMonths // 12 months = numberOfMonths % 12 print(numberOfMonths, "months is", years, "years and", months, "months.") 112. ## Convert lengths. numberOfInches = int(input("Enter number of inches: ")) feet = numberOfInches // 12 inches = numberOfInches % 12 print(numberOfInches, "inches equals", feet, "feet and", inches, "inches.") EXERCISES 2.3 1. Bon Voyage! 2. Price: $23.45 3. Portion: 90% 4. Python 5. 1 x 2 x 3 6. tic-tac-toe 7. father-in-law 8. father-in-law 9. T-shirt 10. spam and eggs 11. Python 12. on-site repair 13. Hello 14. Hello 15. One Two Three Four World! World! 16. 1 2 3 17. NUMBER SQUARE 18. COUNTRY LAND AREA Detroit Lions 2 4 India 2.5 million sq km Indianapolis Colts 3 9 China 9.6 million sq km 19. Hello World! 20. STATE CAPITAL 21. 01234567890 Hello World! North Dakota Bismarck A B C South Dakota Pierre Enter a sentence: Live long and prosper. Enter word to replace: prosper Enter replacement word: proper Live long and proper. Enter number of months: 234 234 months is 19 years and 6 months. Enter number of inches: 185 185 inches is 15 feet and 5 inches. © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 9. Instructor Solutions Manual (Page 11 of 212) 22. 0123456789012345 23. 01234567890123456 24. 01234567890 one two three one two three A B C 25. 0123456789 26. 0123456789 12.30% 1,234 123.0% 1,234 1,230.00% 1,234 27. $1,234.57 28. 1,234 29. 1 30. #1,234.00 31. Language Native speakers % of World Pop. Mandarin 935,000,000 14.10% Spanish 387,000,000 5.85% English 365,000,000 5.52% 32. Major Percent of Students Biology 6.2% Psychology 5.4% Nursing 4.7% 33. Be yourself – everyone else is taken. 34. Plan first, code later 35. Always look on the bright side of life. 36. And now for something completely different. 37. The product of 3 and 4 is 12. 38. The chances of winning the Powerball Lottery are 1 in 175,223,510. 39. The square root of 2 is about 1.4142. 40. Pi is approximately 3.14159. 41. In a randomly selected group of 23 people, the probability is 0.51 that 2 people have the same birthday. 42. The cost of Alaska was about $10.86 per square mile. 43. You miss 100% of the shots you never take. - Wayne Gretsky 44. 12% of the members of the U.S. Senate are from New England. 45. 22.28% of the UN nations are in Europe. 46. The area of Alaska is 17.5% of the area of the U.S. 47. abracadabra 48. When you have nothing to say, say nothing. 49. Be kind whenever possible. It is always possible. - Dalai Lama 50. If you can dream it, you can do it. - Walt Disney © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 10. Instructor Solutions Manual (Page 12 of 212) 51. Yes 52. Yes 53. ## Calculate a server's tip. bill = float(input("Enter amount of bill: ")) percentage = float(input("Enter percentage tip: ")) tip = (bill * percentage) / 100 print("Tip: ${0:.2f}".format(tip)) 54. ## Calculate income. revenue = eval(input("Enter revenue: ")) expenses = eval(input("Enter expenses: ")) netIncome = revenue - expenses print("Net income: ${0:,.2f}".format(netIncome)) 55. ## Calculate a new salary. beginningSalary = float(input("Enter beginning salary: ")) raisedSalary = 1.1 * beginningSalary cutSalary = .9 * raisedSalary percentChange = (cutSalary - beginningSalary) / beginningSalary print("New salary: ${0:,.2f}".format(cutSalary)) print("Change: {0:.2%}".format(percentChange)) 56. ## Calculte a change in salary. beginningSalary = float(input("Enter beginning salary: ")) raisedSalary = 1.05 * 1.05 * 1.05 * beginningSalary percentChange = (raisedSalary - beginningSalary) / beginningSalary print("New salary: ${0:,.2f}".format(raisedSalary)) print("Change: {0:.2%}".format(percentChange)) 57. ## Calculate a future value. p = float(input("Enter principal: ")) r = float(input("Enter interest rate (as %): ")) n = int(input("Enter number of years: ")) futureValue = p * (1 + (r / 100)) ** n print("Future value: ${0:,.2f}".format(futureValue)) Enter amount of bill: 45.50 Enter percentage tip: 20 Tip: $9.10 Enter beginning salary: 42500 New salary: $42,075.00 Change: -1.00% Enter principal: 2500 Enter interest rate (as %): 3.5 Enter number of years: 2 Future value: $2,678.06 Enter beginning salary: 35000 New salary: $40,516.88 Change: 15.76% Enter revenue: 550000 Enter expenses: 410000 Net income: $140,000.00 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 11. Instructor Solutions Manual (Page 13 of 212) 58. ## Calculate a present value. f = float(input("Enter future value: ")) r = float(input("Enter interest rate (as %): ")) n = int(input("Enter number of years: ")) presentValue = f / ((1 + (r / 100)) ** n) print("Present value: ${0:,.2f}".format(presentValue)) EXERCISES 2.4 1. Pennsylvania Hawaii 2. New Jersey, Arizona 3. Alaska Hawaii 4. 50 5. Delaware Delaware 6. 0 7. 48 8. 22 9. Ohio 10. Hawaii Hawaii 11. DELAWARE 12. Puerto Rico 13. ['Puerto Rico'] 14. Georgia 15. United States 16. 48 17. ['New Jersey', 'Georgia', 'Connecticut'] 18. ['Pennsylvania', 'New Jersey', 'Georgia'] 19. ['Oklahoma', 'New Mexico', 'Arizona'] 20. ['New Mexico', 'Arizona', 'Alaska'] 21. ['Delaware', 'Pennsylvania', 'New Jersey', 'Georgia'] 22. ['Delaware'] 23. ['Arizona', 'Alaska', 'Hawaii'] 24. ['Alaska', 'Hawaii'] 25. [] 26. [] 27. Georgia 28. Arizona 29. ['Alaska', 'Hawaii'] 30. Massachusetts 31. New Mexico 32. New Jersey 33. 10 34. 30 35. 0 36. 50 37. 48 38. 46 39. ['Hawaii', 'Puerto Rico', 'Guam'] 40. ['Alaska', 'Hawaii', ['Puerto Rico', 'Guam']] 41. ['Hawaii', 'Puerto Rico', 'Guam'] 42. ['Arizona', "Seward's Folly", 'Hawaii'] 43. ['Delaware', 'Commonwealth of Pennsylvania', 'New Jersey'] 44. ['Delaware', 'Commonwealth of Pennsylvania', 'Pennsylvania'] 45. ['New', 'Mexico'] 46. ['Jersey', 'New', 'Mexico'] ['New', 'Jersey'] Enter future value: 10000 Enter interest rate (as %): 4 Enter number of years: 6 Present value: $7,903.15 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 12. Instructor Solutions Manual (Page 14 of 212) 47. Pennsylvania,New Jersey,Georgia 48. ['Jersey', 'New', 'Mexico'] 49. 8 50. 8 51. 100 52. 7 53. 0 54. 98 55. Largest Number: 8 56. Smallest Number: 0 57. Total: 16 58. Average 4.0 59. This sentence contains five words. This sentence contains six different words. 60. ['all', 'for', 'one'] 61. Babbage, Charles 62. Guido Rossum 63. Middle Name: van 64. Python 65. When in the course of human events 66. Less is more. 67. editor-in-chief 68. merry-go-round 69. e**pluribus**unum 70. ['around', 'the', 'clock'] 71. ['New York', 'NY', 'Empire State', 'Albany'] 72. ['France', 'England', 'Spain'] 73. ['France', 'England', 'Spain'] 74. a bcd 75. programmer 76. Live let live. 77. Follow your own star. 78. Largest Number: 8 Length: 4 Total: 16 Number list: [6, 2, 8, 0] 79. 987-654-3219 80. Dairy 81. [3, 9, 6] 82. (-5, 17, 123) 83. each 84. (0, 2, 3) 85. ['soprano', 'tenor', 'alto', 'bass'] 86. ['soprano', 'tenor', 'alto', 'bass'] 87. ['gold', 'silver', 'bronze'] 88. ['gold', 'silver', 'bronze'] 89. murmur 90. [0, 0, 0, 0] 91. ('Happy', 'Sneezy', 'Bashful') 92. ['Nina', 'Pinta'] 93. 1 94. 2 95. Index out of range. The list does not have an item of index 3. 96. The statement word[1] = 'p' is not valid since strings are immutable. 97. The join method only can be applied to a list consisting entirely of strings. 98. The tuple does not have an item of index 4. 99. The second line is not valid. Items in a tuple cannot be reassigned values directly. 100. Tuples do not support the append method. © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 13. Instructor Solutions Manual (Page 15 of 212) 101. ## Count the number of words in a sentence. sentence = input("Enter a sentence: ") L = sentence.split(" ") print("Number of words:", len(L)) 102. ## Analyze a sentence sentence = input("Enter a sentence: ") L = sentence.split() print("First word:", L[0]) print("Last word:", L[-1][:-1]) 103. ## Display a name. name = input("Enter a 2-part name: ") L = name.split() print("{0:s}, {1:s}".format(L[1], L[0])) 104. ## Extract the middle name from a three-part name. name = input("Enter a 3-part Name: ") L = name.split() print("Middle Name:", L[1]) PROGRAMMING PROJECTS CHAPTER 2 1. ## Make change for an amount of less than one dollar. amount = int(input("Enter amount of change: ")) remainder = amount quarters = remainder // 25 remainder %= 25 dimes = remainder // 10 remainder %= 10 nickels = remainder // 5 remainder %= 5 cents = remainder print("Quarters:", quarters, end=" ") print("tDimes:", dimes) print("Nickels:", nickels, end=" ") print("tCents:", cents) Enter a sentence: This sentence contains five words. Number of words: 5 Enter a 2-part name: Charles Babbage Revised form: Babbage, Charles Enter amount of change: 93 Quarters: 3 Dimes: 1 Nickels: 1 Cents: 3 Enter a 3-part name: Augusta Ada Byron Middle name: Ada Enter a sentence: Reach for the stars. First word: Reach Last word: stars © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 14. Instructor Solutions Manual (Page 16 of 212) 2. ## Determine the monthly payment for a car loan. loanAmount = float(input("Enter amount of loan: ")) interestRate = float(input("Enter interest rate (%): ")) numYears = float(input("Enter number of years: ")) i = interestRate / 1200 monthlyPayment = (i / (1 - ((1 + i) ** (-12 * numYears)))) * loanAmount print("Monthly payment: ${0:,.2f}".format(monthlyPayment)) 3. faceValue = float(input("Enter face value of bond: ")) couponRate = float(input("Enter coupon interest rate: ")) interest = faceValue * couponRate marketPrice = float(input("Enter current market price: ")) yrsUntilMaturity = float(input("Enter years until maturity: ")) a = (faceValue - marketPrice) / yrsUntilMaturity b = (faceValue + marketPrice) / 2 ytm = (interest + a) / b print("Approximate YTM: {0:.2%}".format(ytm)) 4. ## Determine the unit price of a purchase. price = float(input("Enter price of item: ")) print("Enter weight of item in pounds and ounces separately.") pounds = float(input("Enter pounds: ")) ounces = float(input("Enter ounces: ")) weightInOunces = 16 * pounds + ounces pricePerOunce = price / weightInOunces print("Price per ounce: ${0:.2f}".format(pricePerOunce)) 5. ## Describe the distribution in a stock portfolio. spy = float(input("Enter amount invested in SPY: ")) qqq = float(input("Enter amount invested in QQQ: ")) eem = float(input("Enter amount invested in EEM: ")) vxx = float(input("Enter amount invested in VXX: ")) total = spy + qqq + eem + vxx print() print("{0:6s}{1:>12s}".format("ETF", "PERCENTAGE")) print("-" * 18) Enter amount of loan: 12000 Enter interest rate (%): 6.4 Enter number of years: 5 Monthly payment: $234.23 Enter face value of bond: 1000 Enter coupon interest rate: .04 Enter current market price: 1180 Enter years until maturity: 15 Approximate YTM: 2.57% Enter price of item: 25.50 Enter weight of item in pounds and ounces separately. Enter pounds: 1 Enter ounces: 9 Price per ounce: $1.02 © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
  • 15. Instructor Solutions Manual (Page 17 of 212) print("{0:6s}{1:10.2%}".format("SPY", spy / total)) print("{0:6s}{1:10.2%}".format("QQQ", qqq / total)) print("{0:6s}{1:10.2%}".format("EEM", eem / total)) print("{0:6s}{1:10.2%}".format("VXX", vxx / total)) print() print("{0:s}: ${1:,.2f}".format("TOTAL AMOUNT INVESTED", total)) 6. ## Convert a measurement from miles, yards, feet, ## and inches, to a metric one in meters, kilometers, ## and centimeters. miles = float(input("Enter number of miles: ")) yards = float(input("Enter number of yards: ")) feet = float(input("Enter number of feet: ")) inches = float(input("Enter number of inches: ")) # Step #1: Add up given measurements into inches totalInches = inches + 12 * feet + 36 * yards + 63360 * miles # Step #2: Convert total inches into total meters totalMeters = totalInches / 39.3700787 # Step #3: Compute kilometers, whole meters, and centimeters # Step 3a: compute # of kilometers, subtract from meters kilometers = int(totalMeters / 1000) totalMeters = totalMeters - 1000 * kilometers meters = int(totalMeters) centimeters = 100 * (totalMeters - meters) centimeters = round(centimeters, 1) print("Metric length:") print(" ", kilometers, "kilometers") print(" ", meters, "meters") print(" ", centimeters, "centimeters") Enter amount invested in SPY: 876543.21 Enter amount invested in QQQ: 234567.89 Enter amount invested in EEM: 345678.90 Enter amount invested in VXX: 123456.78 ETF PERCENTAGE ------------------ SPY 55.47% QQQ 14.84% EEM 21.87% VXX 7.81% TOTAL AMOUNT INVESTED: $1,580,246.78 Enter number of miles: 5 Enter number of yards: 20 Enter number of feet: 2 Enter number of inches: 4 Metric length: 8 kilometers 65 meters 73.5 centimeters © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.