Data Analytics with Python Final Review QUESTIONS

Ace your homework & exams now with Quizwiz!

What is printed by the Python code? def s(x): ----return x * x tot = 0 for n in [1, 3, 5]: ----tot = tot + s(n) print(tot)

35

What will be the output for the following code? a = np.array([1, 2, 3], [0, 1, 4]) print(a.size)

6

Create code to plot a line graph for the average yearly temperatures in US from 2015 to 2019. The x-axis should include years [2015, 2016, 2017, 2018, 2019, 2020]. The average temperatures during these years were [54.4, 54.9, 54.6, 53.5, 52.7, 54.4] respectively. Please arrange the following lines of code in their correct sequence and provide the corresponding numbers. plt.show() ax = fig.add_axes([0,0,1,1]) ax.plot(x, y) fig = plt.figure() x = ['2015', '2016', '2017', '2018', '2019'] y = [54.4, 54.9, 54.6, 53.5, 52.7] import matplotlib.pyplot as plt

6 4 5 2 3 1

You are a computer. What will this line of code print" print(6 + 4 / 2 - (1 * 2)) 3 5 6.0 8.0

6.0

What's the output for the following code? print(len("95637+12")) 95659 15 8 Error

8

Which statement is incorrect? 932 is an integer "False" is a boolean 857.25 is a float "523" is a string

"False" is a boolean

What is the value of x ? x = 0 while (x < 100): x += 2 print(x)

100

If i give you the following code, what will you print out" street_name = "Abbey Road" print(street_name[4] + street_name[7]) yo er en "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road" "Abbey Road"

yo

Given the code below: fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"] groceries = [fruits, vegetables] print(groceries[1][1]) What will be printed? Nectarines" ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"] "Kale" "Spinach" "Strawberries"

"Kale" This question combines several of the Python List concepts that we've seen in the this module. If the code above is at all confusing, I recommend breaking down what's going on using several print statements in your python code. First, try printing out: print(groceries) Then print out: print(groceries[0]) print(groceries[1]) To see what happens at the next stage print out: print(groceries[1][2]) print(groceries[1][3]) I hope this helps clarify how nested lists work.

Given the code below: fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"] groceries = [fruits, vegetables] print(groceries[1][2]) What will be printed?

"Tomatoes"

What is the output from this code snippet? for i in range(0, 10): ----if i % 3 == 0: --------i = 0 ----else: --------i = 1 ----print(i, end=' ')

0 1 1 0 1 1 0 1 1 0

What is the output of the following nested loop? numbers = [10, 20] items = ["Chair", "Table"] for x in numbers: ----for y in items: --------print(x, y)

10 Chair 10 Table 20 Chair 20 Table

What would you predict to be the result of running the following code? def outer_function(a, b): ----def inner_function(c, d): --------return c + d ----return inner_function(a, b) result = outer_function(5, 10) print(result) Syntax Error 10 15 (5, 10)

15 This is because we are calling the `outer_function` and passing in the values 5 and 10 as arguments. Inside the `outer_function`, we define a nested function called `inner_function`. This inner function takes two arguments `c` and `d` and returns their sum. We then return the result of calling `inner_function` with the arguments `a` and `b`. In this case, `a` and `b` are 5 and 10 respectively. So the `inner_function` will be called with the values 5 and 10, and it will return their sum, which is 15. Finally, we assign the result of `outer_function(5, 10)` to the variable `result` and print it. Therefore, the output will be 15.

What will be printed in the console when the following code is run? DO NOT run the code, just pretend to be a computer. def bar(): ----my_variable = 9 ----if 16 > 9: --------my_variable = 16 ----print(my_variable) bar() SyntaxError NameError 16 Nothing will be printed. 9

16

What will be the output for the following code? a = np.array([1, 2, 3, 5, 8]) b = np.array([0, 3, 4, 2, 1]) c = a + b c = c * a print(c[2])

21

What gets printed in the following code? import numpy as np ary = np.array([1,2,3,5,8]) ary = ary + 1 print (ary[1]) 3 4 1 2 5

3

What is Matplotlib in Python?

A data visualization library

Which of the following statements is False? A string delimited by single quotes may include double-quote characters: ----print('Display "hi" in quotes') To avoid using \' and \" inside strings, you can enclose such strings in triple quotes. A string delimited by double quotes can not include double quotes. A string delimited by double quotes may include single quote characters: ----print("Display the name O'Brien")

A string delimited by double quotes can not include double quotes.

Read the code below, what will be printed in the output? score = 60 if score < 80 and score > 70: ----print("A") elif score < 90 or score > 80: ----print("B") elif score > 60: ----print("C")else:print("D") A C D B

B

Which one is NOT a legal variable name in Python? All are correct C_score C-Score _CScore c_Score

C-Score

The following code totals five integers in a list: total = 0 for number in [2, -3, 0, 17, 9]: ----total + number True False

False

What will be printed in the console after running the following code? def my_function(a): ----if a < 40: ---------return --------print("Terrible") ----if a < 80: --------return "Pass" ----else: --------return "Great" print(my_function(25)) "Great" "Pass" NameError None SyntaxError

The code will not print anything to the console because the line `print("Terrible")` is unreachable. When the condition `a < 40` is true, the function immediately returns, and the subsequent code is not executed. Therefore, calling `my_function(25)` will return `None` because there is no explicit return statement in that case.

What will be printed in the console when the following code is run? DO NOT run the code, just pretend to be a computer. def a_function(a_parameter): ----a_variable = 15 ----return a_parameter a_function(10) print(a_variable) NameError 10 15 SyntaxError

The code will throw a NameError when trying to print `a_variable`. This is because `a_variable` is defined within the scope of the `a_function` function and is not accessible outside of it. When the code tries to print `a_variable` outside of the function, it will throw a NameError since `a_variable` is not defined in the outer scope. So the code will execute `a_parameter` as an argument passed to the `a_function`, but it will not be able to print the value of `a_variable` and throw a NameError.

What will be printed in the console when the code is run? DO NOT run the code, just pretend to be a computer. i = 50 def foo(): ----i = 100 ----return i foo() print(i) 100 50 150 NameError

This is because the print statement is outside of the scope of the `foo` function. Inside the `foo` function, a local variable `i` is defined and assigned a value of 100. However, this local variable is not accessible outside of the function scope. Therefore, when we print the value of `i` outside of the function, it will reference the global variable `i` which is initialized to 50.

Given the code below: fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] fruits[-1] = "Melons" fruits.append("Lemons") print(fruits) What do you think will be printed? ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears", "Lemons"] ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Lemons"] ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears", "Melons", "Lemons"] ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Melons", "Lemons"]

["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Melons", "Lemons"]

What is the output of the following code snippet? arr = np.arange(10) sliced_arr = arr[2:7] print(sliced_arr)

[2, 3, 4, 5, 6]

What is the output in the code below? l = list(range(2,11,3)) print(l)

[2, 5, 8]

What will be the output for the following code? a = np.array([[0, 1, 2], [3, 4, 5]]) b = a.sum(axis=1) print(b)

[3, 12]

What gets printed in the following code? import numpy as np a = np.array([[0, 1, 2], [3, 4, 5]]) b = a.sum(axis=1) print (b) [3 12] An error 3 [3, 5, 7] 5

[3,12]

Which line of Python code is valid? a = 12 a : 12 12 = a var a = 12

a = 12

which lines of code will give you an error? name = input("What is your name?") print("Hello, " + name) name = input("What is your name?") print(F"Hello {name}") age = 12 print("You are " + age + " years old")

age = 12 print("You are " + age + " years old")

Which line of code would create a line plot in form of red squares with x = x and y = y? Markers Documentation. https://matplotlib.org/stable/api/markers_api.html

ax.plot(x, y, color='red', marker='s')

What is the method for adding a title to the axes in a Matplotlib plot when the axes object is stored in a variable named ax?

ax.set_title("Axis Title")

Which of A, B, and C gives the same result as the following nested if statement? x = -10 if x < 0: ----print("The negative number ", x, " is not valid here.") else: if x > 0: ----print(x, " is a positive number") --------else: ------------print(x, " is 0") A. x = -10 if x < 0: ----print("The negative number ", x, " is not valid here.") else x > 0: ----print(x, " is a positive number") else: ----print(x, " is 0") B. x = -10 if x < 0: ----print("The negative number ", x, " is not valid here.") elif x > 0: ----print(x, " is a positive number") else: ----print(x, " is 0" C. x = -10 if x < 0: ----print("The negative number ", x, " is not valid here.") if x > 0: ----print(x, " is a positive number") else: ----print(x, " is 0")

b

Which of the following is not a valid way to define this dictionary in Python: d = {'foo': 100, 'bar': 200, 'baz': 300} d = {('foo', 100),('bar', 200),('baz', 300),} d = {} d['foo'] = 100 d['bar'] = 200 d['baz'] = 300

d = {('foo', 100),('bar', 200),('baz', 300),}

Which version of code will output "This will run"? NOTE: The • symbol represents a single space. def my_function(): ••••# This is my function ••••print("This will run") ••••my_function() # This is my program. ••print("This will run") def my_function(): ••••print("This will run") def my_function(): ••••# This is my function ••••print("This will run") my_function()

def my_function(): # This is my function print("This will run") my_function()

Which version of code will produce an Indentation Error when it is run? NOTE: The • symbol represents a single space. def my_function(): print("Hello") def my_function(): ••••print("Hello") def my_function(): ••print("Hello") print("Bye") def my_function(): ••print("Hello")

def my_function(): print("Hello")

Which method is used to get descriptive statistics of a data frame?

describe()

What is a correct syntax to return the first 20 rows of a DataFrame df?

df.head(20)

Floor division (//) divides a numerator by a denominator and yields a floating-point number with a decimal point.

false

In NumPY, we can use dim attribute to get the number of dimensions of a numpy array.

false

In NumPy, we can use dim attribute to get the number of dimensions of a numpy array.

false

In Python, each identifier may consist of letters, digits and underscores (_) but may not begin with an underscore.

false

Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter.

false

What is the data type of the mystery variable? mystery = 734_529.678 list float string integer

float

What is the data type of the result of the variable a in the following line of code? a = int("5") / int(2.7) float str int bool

float

How do you iterate over a range of numbers from 1 to 5 using a for loop? for i in range(1, 6): for i in range(1, 5): for i in range(5): for i in [0, 1, 2, 3, 4, 5):

for i in range(1, 6):

Given the following list: fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] Which line of code will give you "Apples"? fruits[4] fruits[-5] fruits[-4] fruits.Apples() fruits[3]

fruits[-5]

What does the following code print to the console? if 5 > 10: ----print("fan") elif 8 != 9: ----print("glass") else: ----print("cream") Fan glass no output cream

glass

In NumPy, what does the shape of an array mean? The shape is the number of elements in each column. The shape is the number of elements in the array. The shape is the number of elements in each row. The shape is the size of each dimension of the array.

he size of each dimension of the array.

What is the standard way to import matplotlib's pyplot library in python?

import matplotlib.pyplot as plt

Given the nested Python list, which is the correct indexing to grab the word "hello". lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]

lst[3][1][2]

Given the code to create a 2 dimensional array mat below mat = np.arange(1,21).reshape(5,4) Which is the correct way to get the sum of all rows?

mat.sum(axis=1)

Given the code to create a 2 dimensional array mat below mat = np.arange(1,21).reshape(5,4) Write code that produces the output shown below. array([[ 3, 4], [ 7, 8], [11, 12]])

mat[:3, 2:]

Given the code to create a numpy array myarr below create a subset that only contains the even numbers (i.e, every second number) myarr = np.arange(10, 30)

myarr[::2] or myarr_even = np.arange(10, 30, 2)

What is a correct syntax to return the first value of a pandas Series myseries?

myseries[0]

Create a 3x5 matrix with values ranging from 1 to 15

np.arange(1,16).reshape(3,5)

Create an array of 11 linearly spaced points between 0 and 1.

np.linspace(0,1,11)

What is a correct syntax to create a pandas Series from a Python list? mylist = ["Python", "NumPy", "Pandas"]

pd.Series(mylist)

What is the Pandas function used to read a CSV file into a DataFrame?

pd.read_csv()

Which is the best variable name for Player 1s username? 1_player_username = "jackbauer" plauer1_username = "jackbauer" p1 user name = "jackbauer" p1u = "jackbauer"

plauer1_username = "jackbauer"

Which function is used in Matplotlib to create a new figure object?

plt.figure()

What is a correct syntax to print the number 8 from the array below: arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print(arr[1, 2])

What is a correct syntax to print the number 8 from the array below: arr = np.array([[1,2,3,4,5], [6,7,8,9,10]]) print(arr[0, :1] print(arr[1, 2]) print(arr[7, 2]) print(arr[3, 0])

print(arr[1, 2])

What is a correct syntax to print the numbers [3, 4, 5] from the array below: arr = np.array([1,2,3,4,5,6,7])

print(arr[2:5])

Which line of code will produce an error? dict = {"a": 1,"b": 2,"c": 3,}

print(dict[0])

Which line of code will produce an error? dict = { "a": 1, "b": 2, "c": 3,} for key in dict: dict[key] += 1 dict["c"] = [1, 2, 3] dict[1] = 4 print(dict[1])

print(dict[1])

Which line of code will print "Fries"? order = { "starter": {1: "Salad", 2: "Soup"}, "main": {1: ["Burger", "Fries"], 2: ["Steak"]}, "dessert": {1: ["Ice Cream"], 2: []},}

print(order["main"][1][1])

Which line of code will print "Steak"? order = { "starter": {1: "Salad", 2: "Soup"}, "main": {1: ["Burger", "Fries"], 2: ["Steak"]}, "dessert": {1: ["Ice Cream"], 2: []},} print(order[main][2][0]) print(order["main"][2]) print(order["main"][2][0]) print(order["dessert" - 1][2][0])

print(order["main"][2][0])

What is the attribute used to retrieve the number of rows and columns in a DataFrame

shape

Which line of code will change the starting_dictionary to the final_dictionary? starting_dictionary = { "a": 9, "b": 8,} final_dictionary = { "a": 9, "b": 8, "c": 7,}

starting_dictionary["c"] = 7 final_dictionary = starting_dictionary

Which line of code will change the starting_dictionary to the final_dictionary? starting_dictionary = { "a": 9, "b": 8,} final_dictionary = { "a": 9, "b": 8, "c": 7,} final_dictionary = starting_dictionary += {"c": 7} final_dictionary = starting_dictionary["c"]: 7 final_dictionary = starting_dictionary.append({"c": 7}) starting_dictionary["c"] = 7 final_dictionary = starting_dictionary final_dictionary = starting_dictionary["c"] = 7

starting_dictionary["c"] = 7 final_dictionary = starting_dictionary

The data type of rating is ______. rating = input('Enter an integer rating between 1 and 10: ')

string

Give the dataframe temperature, write code to update air quality to 49 specifically for Tuesday.

temperature.at['Tuesday', 'air quality'] = 49

Give the data frame temperature, write code to remove 'air quality' column.

temperature.drop('air quality', axis = 1)

Give the data frame temperature which uses days as customized indices, select the rows for "Monday" and "Friday".

temperature.iloc[[0, 4]] or temperature.loc[["Monday", "Friday"]]

which block of code will produce an error time_until_midnight = "5" print("There are" + time_until_Midnight + "hours until midnight") num_hours = "5" print("There are " num_hours + "hours until midnight") time_until_midnight = "5" print("There are " + time_until_midnight +" hours until midnight")

time_until_midnight = "5" print("There are" + time_until_Midnight + "hours until midnight")

NumPy arrays can only contain elements of a single data type.

true

The following if statement uses the == comparison operator to determine whether the values of variables number1 and number2 are equal: if number1 == number2: ----print(number1, 'is equal to', number2)

true

Python provides two iteration statements— _____ and_____ : do while and for while and for while and for each do while and for each

while and for


Related study sets

Religious Works-J. Gresham Machen

View Set

Access Ch. 1-5 Key Terms Matching

View Set

Macro Econ Exam #2 UofSC Liwen Chen

View Set

World War 2: War in the Pacific Quiz

View Set