Lesson 9 Solutions

9.1 Lesson 1

9.1.1 Quiz 1

1. Which of the following is not an arithmetic operator?

  1. *
  2. **
  3. -
  4. = [CORRECT]
  5. +

2. What is print() in python?

  1. a function [CORRECT]
  2. a class
  3. an object
  4. a string
  5. an operator

3. To write a comment in python, which character would you use?

  1. # [CORRECT]
  2. ##
  3. /
  4. //
  5. /**

4. Which of the following would result in a syntax error?

  1. 3*5
  2. print("Hello) [CORRECT]
  3. print("I'm printing text in python")
  4. max(1,1)
  5. round(22.1)

5. What error would be returned by the following statement? round(150.434321')

  1. NameError
  2. EOL while scanning string literal[CORRECT]
  3. Invalid syntax
  4. No error would be returned

6. What error would be returned by the following statement: round(150.4d34321)

  1. NameError
  2. EOL while scanning string literal c)Invalid syntax [CORRECT]
  3. No error would be returned

7. Price per square foot is the metric used to compare real estate properties in the US. How would you compute price per square foot in python?

  • Selling price = $999,999.00
  • Square footage = 1050 square feet
  1. 999,999 / 1050
  2. 999999 / 1050 [CORRECT]
  3. 999999 * 1050
  4. (999,999 * 1050)
  5. 1050 / 999999

8. How would you round 23,499.9009093 to 2 decimal places?

  1. round(23,499.9009093, 2)
  2. round(23499.9009093, 2) [CORRECT]
  3. round(23499.9009093, 0)
  4. (23,499.9009093, 0)

9. What symbol or set of symbols would you use to include this multi-line comment in your code:

The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

a)#The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.#

b)#The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

c)//The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

d)"""The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.""" [CORRECT]

e)"The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences."

  1. True or False

The following statement returns a value of 7.

max(2,3) + 4 [TRUE]

9.1.2 Exercise 1.1

1. What’s wrong with this code? Provide an explanation and show the corrected code.

min[(2,3,-4,5,6)]

Answer:

_Returns TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

Corrected: min(2,3,-4,5,6)

2. Display the following text to the screen

Hello. Welcome to my python program.

Answer:

print("Hello. Welcome to my python program.")

3.

9.1.3 Exercise 1.2

1. Three MBA students purchased a different asset yesterday at the below listed price. Each sold their asset today at the listed selling price. Calculate the percent return for each student rounded to two decimal points.

Student buy sell
Jen $25.50 $40.20
Jacobi $103.30 $125.00
Mark $86.02 $91.41

Answer

  • Jen:round((((40.20/25.50)-1)*100),2)=57.65%
  • Jacobi: round((((125/103.3)-1)*100),2)=21.01%
  • Mark: round((((91.41/86.02)-1)*100),2)=6.27%

2. Calculate the maximum of the LIST of returns

Answer: max([57.65,21.01,6.27]) = 57.65

9.1.4 Assignment 1

Create a notebook that answers the following questions. Include your name, date, and be sure to document your code using comments.

1a. New York City sales tax on goods and services is 8.875%. Compute the total bill (including sales tax) for the following goods. Round to two decimal places.

  • 1 Macbook pro - $1,299
  • 1 Magic mouse - $79.00
  • Case of copy paper - $24.99

Hint: Order of operations, + and - operators, round() function

1b. Print out the the result from item 1a in a nicely formatted sentence to the user.

Hint: print() function, round() function

9.1.5 Exam questions - Lesson 1

1. What is incorrect with the below code?

Prnt('what error will display?')

  1. nothing this is correct

  2. you cannot use single quotes in Python you must use double

  3. logical error: prnt() is lowercase

  4. syntax error: the correct function is print() [CORRECT]

2. Find c2 given image.png Pythagoreans Theorem calculation:

c2 = a2 + b2 a=5 b=9

  1. (5**2)+(9**2) [CORRECT]
  2. (5^2)+(9^2)
  3. (5^*2)+(9^*2)
  4. (5%2)+(9%2)

3. After graduating NYU you land your dream job making $200,000 per year. Unfortunately you still live in the city. Therefore your Federal, State and City taxes amount to 38%. Calculate your monthly after-tax income.

  1. round(((200,000*(1-.38))//12),2)

  2. round(((200,000*(1-.38))/12),2) [CORRECT]

  3. round((((200,000)(1-.38))/12),2)

  4. round((((200,000)(1-.38))%12),2)

9.2 Lesson 2

9.2.1 Quiz 2

1. How would you assign the integer value of 138 to a variable of named weight?

  1. 138 = weight
  2. weight = 138[CORRECT]
  3. weight = 138.00
  4. weight ="138"
  5. weight ='138'

2. What data type would python assign to distance_run=3.25?

  1. bool
  2. int
  3. str
  4. float [CORRECT]
  5. complex

3. What function would you use to determine the data type of a variable?

  1. str()
  2. print(datatype())
  3. data.type()
  4. class()
  5. type()[CORRECT]

4. Which of the following functions work on only with strings?

  1. upper()
  2. lower()
  3. isupper()
  4. a and b
  5. a,b,and c [CORRECT]

5. What is the data type of this variable: x=True

  1. bool [CORRECT]
  2. str
  3. int
  4. char
  5. float

6. Which statement is correct given name ="Kelly Jones"?

  1. print("Kelly Jones is a customer in our system")
  2. print("Kelly Jones is a", name, "customer in our system")
  3. print('Kelly Jones is a', name, 'customer in our system')
  4. print(name, 'is customer in our system')[CORRECT]
  5. print(name "is customer in our system"")

7. How would you update the following variable named Present to the Boolean value of false?

  1. present = False
  2. present = "false"
  3. Present = False [CORRECT]
  4. Present ='FALSE'
  5. present = False

8. Which of the following statements will result in an error:

  1. int(“3”)
  2. string(3) [CORRECT]
  3. myvariable = int(“3”)
  4. str(3)
  5. str(“mystring”)

9. True or False

variable01="44" and variable02="33".

If you wanted to add variable01 to variable02 and get the result of 77, you would first need to cast variable01 and variable02 to an integer using the int() function and update the variables with the new integer values.

  1. True [CORRECT]
  2. False

10. True or False

The following statement results in a logical error:

annual_rent=3,000

  1. True [CORRECT]
  2. False

9.2.2 Exercise 2.1

1. Building upon exercise 1.2, create variable buy and variable sell for Jen.

2. Restructure your percent return formula using your new variables and assign this to its own ‘tot_return’ variable.

3. What data type is returned by the output (answer) from question 2?

9.2.3 Exercise 2.2

  1. You are working for Facebook’s Operations Intelligence team and are tasked to build a calculator to find the best ad sales representative each month which is based on largest (hint: max) monthly ad revenue. There are 5 sales representatives listed below with this months revenue. Set up the formula so each month you simply change each representatives revenue. Call the calculator rep_calculator

Joe: $1,500,000 Sarah: $2,750,000 Jack: $560,000 Mark: $1,975,000 Shawn: $2,200,000

Answer:

Joe=1500000 Sarah=2750000 Jack=560000 Mark=1975000 Shawn=2200000

rep_calculator=max(Joe, Sarah, Jack, Mark, Shawn)

  1. Print out the following statement using your calculated value: This months Best Ad Sales Representative made: ____________ dollars!

Answer:

print(‘This months Best Ad Sales Representative made:’, ad_calculator, ‘dollars!’)

9.2.4 Assignment 2

1. You work in baseball operations at the NY Mets and are purchasing baseball caps from NewEra for next season. NewEra sells two types of caps, a snapback and a flex cap. The price points for each hat are listed below. Based on forecasted demand for next season you plan to buy 40,000 snapbacks and 70,000 flex hats.

  • Flex=$12.45
  • Snapback=$10.60

Create variables for: snap_num (the number of snap caps), flex_num (the number of flex caps), along with the corresponding prices: snap_px, flex_px.

2. Create a total_cost variable that represents the total cost of your purchase of both hat types.

3. After running some analysis you realize that snapbacks are even less popular this year and you decide to reduce the number of snapbacks by 10,000 and increase the flex hats by 10,000. Adjust your variables for this change and calculate a new total cost.

9.2.5 Exam questions - Lesson 2

** 1. What data type is the following variable?**

aapl=202.59

  1. int
  2. float [CORRECT]
  3. Str
  4. tuple
  5. num

** 2. The following code is entered into Python:

goog=500 amzn=100 cat=350 xom=550 jpm=600 max_shares=max(goog, amzn, cat, xom, jpm) print(max_shares)

What is the output of the Python code above?

  1. SyntaxError
  2. Jpm
  3. 600 [CORRECT]
  4. NameError

3. Which statement below calculates the average jersey price?

Rivera=134.99 Alonso=124.99 Harper=119.99 Bregman=119.99 Betts=124.99

  1. nd(((Rivera+Alonso+Harper+Bregman+Betts)/5),2)
  2. round(((Rivera+Alonso+Harper+Bregman+Betts)//5),2)
  3. rnd(((Rivera+Alonso+Harper+Bregman+Betts)//5),2)
  4. round(((Rivera+Alonso+Harper+Bregman+Betts)/5),2) [CORRECT]

9.3 Lesson 3

9.3.1 Quiz 3

1. Which of the following is not a data structure in python?

  1. int [CORRECT]
  2. tuple
  3. Series
  4. DataFrame

Feedback: DataFrame, tuple, List, and Series are all data structures used in python. An int is a data type.

2. What is one disadvantage of using a tuple to store data?

  1. tuples only allow for homogeneous data types
  2. you can not name tuples
  3. tuples are immutable [CORRECT]
  4. all of the above

Feedback: Tuples allow for heterogeneous data and can be assigned to named variable. However, tuples cannot be updated or changed. They are immutable.

3. The following expression creates a data object of what type?

x = (23, 32, "Hello", "Goodbye")

  1. variable
  2. tuple [CORRECT]
  3. Series
  4. DataFrame

Feedback: Assignment of a set of values enclosed in parentheses and separated by commas results a data object or structure of type tuple.

4. Python uses a non-zero based indexing.

  1. True
  2. False [CORRECT]

Python uses zero-based indexing. For example, the index of the first value in a List or at tuple is 0.

5. How would you access the 5th element in this tuple?

mytuple = (22,45,21,212,21,341,1231,31,43,23)

  1. mytuple(4)
  2. mytuple [5]
  3. mytuple[21]
  4. mytuple[4] [CORRECT]

Feedback: To access the fifth element pass in the index of 4, not 5 using the square brackets.

6. How would you determine the length of a given tuple named myspend?

  1. length(myspend)
  2. len(myspend) [CORRECT]
  3. len[myspend)
  4. myspend.len()

Feedback: Use the len() function to determine the length of a tuple, string, or List. The len() function takes the tuple, string, or List as a parameter.

7. How would you convert the tuple x=(99,100,89,72) to a List?

  1. tuple(x) = list(x)
  2. mylist = tuple(x)
  3. mylist = list(x) [CORRECT]
  4. list(x) = x

Feedback: Use the list() function to cast or convert the tuple to a List and then assign the result to a variable.

8. Given the List below, how would you change the single value of 89 to 92?

grades = [100, 91, 90, 89, 76, 80]

  1. grades[3] = 92 [CORRECT]
  2. grades = [92]
  3. grades = [100, 91, 90, 92, 76, 80]
  4. grades(3) = 92
  5. grades[4] = 92

Feedback: Update the fourth element at index position 3 to the value of 92.

9. How would you add a new value of 100 to the list below?

grades = [100, 91, 90, 89, 76, 80]

  1. grades = (100)
  2. grades = [100]
  3. grades = 100
  4. grades += [100] [CORRECT]

Feedback: To add an element to a List, use the += operator for assignment to the List.

10. How would you remove the value 80 from the list below?

grades = [100, 91, 90, 89, 76, 80, 100]

  1. del grades[5]
  2. grades.pop(5)
  3. grades.remove(80)
  4. all of the above [CORRECT]

Feedback: You could use all of the above approaches to delete an element either by index or value.

9.3.2 Exercise 3.1

  1. Create two Lists with the following data.
Month Amount
January 230
February 250
March 345
April 290
May 890
June 321
July 232
August 456
September 213
October 299
November 123
December 566
  1. Update the amount for April from 290 to 302

  2. Use indexing to reference the amount April from your month list and it’s corresponding amount 302 from the amount list. Print those values in a sentence that reads:

You spent $302 in April.

  1. Add 2 new values to your Lists. The new value for the month list should be total and the new value to be added to the amount list is the sum of all values in the list.

Print those new variables out in a sentence that reads:

The total annual spend on consumable goods was $4215.

9.3.3 Exercise 3.2

  1. Create 2 tuples for the following data: date and precipitation
Date Precipitation
21-Jul Sun
22-Jul Rain
23-Jul Rain
24-Jul Sun
25-Jul Sun
26-Jul Sun
27-Jul Sun
28-Jul Sun
29-Jul Sun
30-Jul Sun
31-Jul Rain
1-Aug Rain
2-Aug Rain
3-Aug Rain
  1. Convert both tuples into lists date_list, precipitation_list.

  2. Count the number of days included in this list.

  3. Separate the lists into two lists one for week1 and one for week2 (total of 4 lists)

  4. Using indexing for week2_precipitation, what will the weather be on July 30th?

9.3.4 Assignment 3

Using the data from Exercise 3.2, replace the each value of Rain with 1 and each value of Sun with a 0.

  1. How many days in the 2 week time span will it rain and how many days will it be sunny?

  2. The weather can now be predicted for August 4th and 5th. Aug 4th will be sunny and Aug 5th will rain, add both dates to the data.

Print the following statements using indexing:

On 4-Aug we will see the sun. On 5-Aug we will see rain.

9.3.5 Exam questions - Lesson 3

1.What error would you see given the following code:

date=(‘Sunday’, ‘July’, 21, 2019)

  1. SyntaxError
  2. NameError
  3. No error [CORRECT]
  4. KeyboardInterrupt

2.Slice the given list so that you will no longer see Sunday

dateList=["Sunday", "July", 21, 2019]

  1. dateList=dateList[1:4] [CORRECT]
  2. dateList=dateList(1:3)
  3. dateList=datelist[1:3]
  4. dateList=dateList[2:4]

3. How would you properly remove index 2 from the following tuple?

tuple=(24, 28, 29, 32, 36)

a).pop(2) b) del tuple[2] c).remove(29) d) You cannot remove data from a tuple, you can only do this after converting to a list.

9.4 Lesson 4

9.4.1 Quiz 4

1. True or False. An object is an instance of a class

  1. True [CORRECT]
  2. False

Feedback: An object is an instance of a class. The class defines the methods that can alter the behaviors of the object and its attributes.

2. Which of the following manipulate data attibutes of an object?

  1. instance
  2. method [CORRECT]
  3. class
  4. object
  5. library

Feedback: Methods are defined by the object’s class and are used to alter the behaviors and attributes of the object.

3. True or False. Pandas is part of python’s built-in library

  1. True
  2. False [CORRECT]

Feedback: The answer is False. Pandas is not part of python’s built-in library. It is a separate library.

4. Which of the following is incorrect?

  1. import pandas as pineapples
  2. import pandas as pd
  3. import pd as pandas [CORRECT]
  4. import pandas as pandaspops

Feedback: When importing the pandas library use import pandas as whatevernameuyoulike

5. Which method would use to import a .csv file into python?

  1. read_csv() [CORRECT]
  2. read.csv()
  3. readcsv()
  4. read_csv.mydata()

Feedback: Use the read_csv method from the pandas library to read in a .CSV file into python as a DataFrame.

6. How would you preview the first 9 rows of data in your Data Frame named coffeeshops?

  1. coffeeshops.tail(9)
  2. coffeeshops[9]
  3. coffeeshops(9)
  4. coffeeshops.head(9)[CORRECT]
  5. head.coffeeshops(9)

Feedback: The head() function is used to show the beginning of a DataFrame. It takes the parameter which is the number of rows to show.

7. How could you just show the number of rows and columns of a Data Frame

  1. .shape [CORRECT]
  2. .info()
  3. .columns()
  4. .row()

Feedback: By calling .shape you can access the rows and columns data attribute of a DataFrame object.

8. What would be the output from the following code?

import pandas as pd
movies = pd.read_csv("movies.csv", header=0) 
movietitle = movies[1]
type(movietitle)

Feedback: A Series is returned when extracting a single column from a DataFrame using a single set of square brackets. a) class 'pandas.core.tuple.List' b) class 'pandas.core.tuple.Tuple' c) class 'pandas.core.frame.DataFrame' d) class 'pandas.core.series.Series'[CORRECT]

9. What is the correct syntax for extracting a column from a DataFrame if you want the extracted column to be of type DataFrame?

  1. mycolumn = mydataframe([1])
  2. mycolumn [1] = mydataframe[1]
  3. mycolumn = mydataframe[1]
  4. mycolumn = mydataframe[[1]] [CORRECT]

Feedback: Use the double set of square brackets to extract a single column from a DataFrame and return a DataFrame.

10. What’s the difference between .loc an .iloc

  1. .loc returns by row name,
  2. .iloc returns by row index
  3. .iloc ranges are exclusive of the last element
  4. .loc ranges are inclusive of the last element
  5. All of the above [CORRECT]

Feedback: All of the above choices describe the differences between iloc and loc.

9.4.2 Exercise 4.1

  1. Download the portfolio.csv file from http://becomingvisual.com/python4data/portfolio.csv and import it into Python.
  2. What are the data types of each column?
  3. How many columns and rows are in your portfolio dataframe?
  4. Rename the first column in the dataframe to Security

ANSWER: import pandas as pd portfolio=pd.read_csv(“portfolio.csv”, header=0) portfolio.info() portfolio.shape portfolio.columns=[‘Security’, ‘Price’, ‘Weight’, ‘Shares’]

9.4.3 Exercise 4.2

  1. You decide to purchase 5 more shares of V, change the number of V shares to 55 (hint: row 9 of the Shares column df.loc[row #, ‘column name’]=new value)

  2. Add a new column to your dataframe that calculates the’ market_value’ of each security (hint: portfolio.Price*portfolio.Shares)

  3. Use the .sum() function to sum the total of your new market_value column to find the value of your portfolio and call this variable ‘total_value’

ANSWER: portfolio.loc[9,’Shares’]=55 portfolio[‘market_value’]=portfolio.Price*portfolio.Shares total_value= portfolio[‘market_value’].sum()

9.4.4 Assignment 4

  1. Down the windenergy.csv file from http://becomingvisual.com/python4data/windenergy.csv and import it into python. This data breaks down utility scale of wind turbines per state in the US.

  2. Print out the top 10 states utilizing the most wind power.

  3. Create a new dataframe that pulls in State, Ranking, Installed Capacity, Num of Turbines, and Homes Powered

  4. Pull in the data for our great state of New York!

ANSWER:

  1. import pandas as pd energyCapacity=pd.read_csv(“windenergy.csv”, header=0)

  2. energyCapacity.head(10)

  3. energyCapacityNew=energyCapacity[[‘State’, ‘Ranking’, ‘Installed Capacity (MW)’, ‘# of Wind Turbines’, ‘Equivalent Homes Powered’]] energyCapacityNew.columns= [‘State’, ‘Ranking’, ‘Installed Capacity’, ‘Num of Turbines’, ‘Homes Powered’]

  4. NY= energyCapacityNew.loc[‘New York’] or .iloc[13]

9.4.5 Exam questions - Lesson 4

1.Which method would not be used with the following object?

Attributes: type, size, price, quantity Tuple(4)

order=['Cold_Brew', 'Tall', 2.65, 3]

  1. total=order[2]*order[3]
  2. order.append(total)
  3. order.upper() CORRECT
  4. order=tuple(order)
  1. How would you import the below orderTable.csv into Python?

  1. import pd as pandas orderTable=pd.read_csv(“orderTable.csv”, header=0)
  2. import pandas as pd orderTable=pd.read_csv(“orderTable.csv”, header=0) CORRECT
  3. import pandas as pd orderTable=pandas.read_csv(“orderTable.csv”, header=0)
  4. import pandas as pd orderTable=pd.read_csv(“orderTable.csv”, header=1)
  1. Using the orderTable how would you create a new dataframe which excludes completed and outstanding orders?
  1. newOrders=orderTable[[‘Time’, ‘New Orders’]] CORRECT

  2. newOrders=orderTable([‘Time’, ‘New Orders’])

  3. newOrders=orderTable-[[‘Completed Orders’, ‘Outstanding Orders’]]

  4. newOrders=orderTable-([‘Completed Orders’, ‘Outstanding Orders’])

9.5 Lesson 5

9.5.1 Quiz - Lesson 5

1. Evaluate the following statement:

8 == 8

  1. TRUE
  2. True [CORRECT]
  3. true
  4. FALSE
  5. Not False

Feedback: The the value of 8 is equal to 8. This Boolean operator returns a value of True.

2. Evaluate the following statement:

8 =! 8

  1. False
  2. FALSE
  3. false
  4. SyntaxError: invalid syntax [CORRECT]
  5. True

Feedback: Correct. This =! results in an invalid syntax error. The corrected syntax is !=.

3. Evaluate the following statement: (32*2==64) and (8**2==64)

  1. False
  2. True [CORRECT]
  3. TRUE
  4. FALSE
  5. SyntaxError: invalid syntax

Feedback: Correct. Both expressions in the parentheses result in 64 and 64 equals 64.

4. Which statement will provide a syntax error given that x=4

  1. x>=4 and x<5
  2. (x>=4) and (x<5)
  3. ((x>=4) and (x<5))
  4. ((x>=4) and (x<!5)) [CORRECT]

Feedback: Choice d, produces a syntax error. x<! is a syntax error.

5. What type of object will be returned from this statement:

condition = [mydata[mydata['AvgSalary'] >=125000]]

  1. List [CORRECT]
  2. Series
  3. Data Frame
  4. Tuple
  5. Array

Feedback: This statement produces an object of type List. List objects values are enclosed in square brackets.

6. What type of object will be returned from this statement:

condition = mydata[mydata['AvgSalary'] >=125000]

  1. List
  2. Series
  3. Data Frame [CORRECT]
  4. Tuple
  5. Array

Feedback: The object is a Data Frame.

7. What type of object will be returned from this statement:

condition = mydata['AvgSalary'] >=125000

  1. List
  2. Series [CORRECT]
  3. Data Frame
  4. Tuple
  5. Array

Feedback: A Series is returned when square brackets are not used around the entire expression assigned to the variable.

8. The for statement is an example of a control structure

  1. TRUE [CORRECT]
  2. FALSE

9. Which is not a comparison operator

  1. ==
  2. !=
  3. = [CORRECT]
  4. >
  5. <

Feedback: The = equals sign in an assignment operator not a comparison operator.

10. What’s wrong with the following code?

counter = 0
while counter < 3:
    print("Inside loop")
    counter = counter
else:
    print("Inside else")
  1. Nothing
  2. the counter does not decrement causing an infinite loop
  3. the counter does not increment causing an infinite loop [CORRECT]
  4. The code produces a syntax error
  5. the else should be indented

Feedback: The counter does not increment as the expression after the while statement is evaluated. Therefore, counter is always less than 3 and the loop is infinite.

9.5.2 Exercise 5.1

  1. Filter the mba DataFrame to show only those schools where the Average salary is less than to $100,000 and the tution is greater than equal to $100,000.

9.5.3 Exercise 5.2

9.5.4 Assignment 5

9.5.5 Exam questions