CSCI - 5334 Midterm practice

¡Supera tus tareas y exámenes ahora con Quizwiz!

import numpy as np random_numbers = np.random.rand(10) print(random_numbers)

You don't need to explicitly specify that the numbers should be between 0 and 1 when using np.random.rand(10). This function by default generates random numbers between 0 (inclusive) and 1 (exclusive).

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) 150 100 50 NameError

50 The print statement is outside the function foo(). So it can't access the local variable i = 100. It only sees the global i, which is equal to 50. The key point to note is that the global variable i and the local variable i inside the foo() function are separate and have different scopes. The local variable i does not affect the global variable i. So, when print(i) is executed, it refers to the global variable i, which remains 50.

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

6.0

Using a NumPy function, how would you create a one-dimensional NumPy array of the numbers from 10 to 100.

import numpy as np a = np.arange(10, 101) print(a)

array = ([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) Given above array, write an expression to print the last row.

import numpy as np array = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) # Print the last row print(array[-1])

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 - because of '" ", should be just - False

I've put a spell on you. You are now a computer. If I give you the following code, what will you print out? street_name = "Abbey Road" print(street_name[4] + street_name[7]) open ended

yo A = o space = 1

What will be the output of following code? import pandas as pd series1 = pd.Series([10,20,30,40,50]) print (series1) None of these 0 10 1 20 2 30 3 40 4 50 dtype: int64 1 10 2 20 3 30 4 40 5 50 dtype: int64 0 10 1 20 2 30 3 40 4 50 dtype: float32

0 10 1 20 2 30 3 40 4 50 dtype: int64

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) 15 10 Syntax Error (5, 10)

15 a = 5, which means c = 5. b = 10, which means d = 10. The output of inner_function becomes the output of outer_function The result of inner_function(a, b) (i.e., 15) becomes the result of outer_function, and it's assigned to the result variable.

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()

16 Remember that in Python there is no block scope. Inside a if/else/for/while code block is the same as outside it.

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

3 Here's how it works: You perform element-wise addition by adding 1 to each element in the ary array. This operation effectively adds 1 to every element in the array. Finally, you print ary[1], which accesses the second element of the modified array. The second element of the modified array is 2 + 1, which equals 3.

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

8 in a string, spaces and special characters like "+" are considered characters just like letters and numbers. So, in the string "95637+12," there are 8 characters in total, which include the digits '9', '5', '6', '3', '7', '1', '2', and the plus sign '+'.

Which of the following statements is true? gender = "Female" age = 70 if gender == "Female" and age >= 65: print("Senior Female") The right side of the and operator evaluates only if the left side is True. The combined condition can be made clearer by adding redundant (unnecessary) parentheses (gender == 'Female') and (age >= 65) The code defines two variables, then tests a condition that's True if and only if both simple conditions are True—if either (or both) of the simple conditions

All of the statements are true.

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")

B Because elif score < 90 or score > 80: In this condition, the code will check if score is either less than 90 or greater than 80. Since the value of score is 60, it is indeed less than 90, and the condition is satisfied.

Which of the following statements create a dictionary? All of the mentioned d = {} d = {"john":40, "peter":45} d = {40:"john", 45:"peter"}

Correct! All of the mentioned

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 [3, 5, 7] [3 12] An error 5

Correct! [3 12] You use the sum() method with the axis=1 argument on the a array. This calculates the sum along axis 1, which corresponds to the rows. It sums the values within each row separately, resulting in a new NumPy array b. The b array contains the sums of each row, which are [0+1+2, 3+4+5], resulting in [3, 12]. Finally, you print the b array, and it is displayed as [3 12]. **axis=0 calculates the sum along the rows (resulting in sums for each column). axis=1 calculates the sum along the columns (resulting in sums for each row).

What will be the output of the following Python code? x = 123 for i in x: print(i) 1 2 3 123 1, 2, 3 Error

Error In Python, you need to convert the integer to a string to iterate over its individual digits because integers are not iterable by default. When you iterate over an integer, Python doesn't treat it as a sequence of its digits but rather as a single value. As a result, Python raises a TypeError because you are attempting to iterate over a non-iterable object (an integer). correct would be: x = 123 for i in str(x): print(i)

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

False To fix this code and correctly total the integers, you should use the += operator to update the total variable with the sum of each number in the list within the loop, should be total += number

What is the data type of the mystery variable? mystery = 734_529.678 String Integer Float List

Float

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

In this code, there are no actual numbers being compared; the conditions are static comparisons, and the numbers "5," "10," "8," and "9" are simply used as placeholders. The values being compared in the conditions themselves don't affect the output. In the code provided: The if statement condition is 5 > 10, which is false. The code block under the if statement is not executed. The elif statement condition is 8 != 9, which is true. Therefore, the code block under the elif statement is executed, and "glass" is printed to the console.

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) 10 NameError 15 SyntaxError

NameError It's trying to print a variable that is local to a_function() and is only available inside the function. ameError: A NameError occurs when you try to access a variable or identifier that has not been defined or is not in the current scope. It means that Python doesn't recognize the name you are trying to use. Common causes of NameError include using a variable before it's defined, misspelling a variable or function name, or trying to access a variable outside of its scope. Example of a NameError: print(x) # Using the variable 'x' before it's defined

What is the order of precedence in python? Group of answer choicesParentheses, Exponential, Multiplication, Division, Addition, SubtractionParentheses, Exponential, Multiplication, Division, Subtraction, AdditionExponential, Parentheses, Division, Multiplication, Addition, SubtractionExponential, Parentheses, Multiplication, Division, Addition, Subtraction

PEMDAS Parentheses, Exponential, Multiplication, Division, Addition, Subtraction

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

So, the expression int("5") / int(2.7) becomes 5 / 2, which is a division of two integers. However, because one of the operands is a float (2.7 originally), the division operation results in a float value. Therefore, the data type of the variable a is a float.

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" SyntaxError NameError "Pass" None

The return keyword will exit the function and prevent the rest of the code from being executed. Because the return statement doesn't specify any value to return, it effectively returns - None.

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 each row. The shape is the size of each dimension of the array. The shape is the number of elements in the array.

The shape is the size of each dimension of the array.

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?

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]) print(groceries[1][1]) - > vegetables -> "Kale"

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", "Melons", "Lemons"] Here's the explanation: The initial list fruits contains the following elements: ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] The line fruits[-1] = "Melons" replaces the last element in the list (which is "Pears") with "Melons." The line fruits.append("Lemons") adds "Lemons" to the end of the list. The final list is then printed, resulting in the list: ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Melons", "Lemons"] The append method in Python, when used with lists, adds the specified element to the end of the list. This is the default behavior of the append method, and it is a common operation to add new elements to the end of a list because it's an efficient process. If you want to add an element to the beginning of a list, you can use the insert method to specify the position where you want to insert the element.

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

a = 12 var a = 12 would need to be var_a to be valid ?

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

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

What is the correct way to create a function in Python? def myFunction(): myFunction() function myFunction(): def myFunction() { }

def myFunction():

What is the correct way to create a function in Python? Group of answer choicesdef myFunction():myFunction()function myFunction(): def myFunction() { }

def myFunction():

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") print("Bye") def my_function(): print("Hello") def my_function(): ••••print("Hello") def my_function(): ••print("Hello")

def my_function(): print("Hello")

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() def my_function(): ••••# This is my function ••••print("This will run")my_function() def my_function(): ••••print("This will run") # This is my program. ••print("This will run")

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

Amongst which of the following is / are not correct to access a row from dataframe 'df'. You Answered df.at[2] df.iloc[2] df.loc[2] df[0]

df[0] df.at[2] are incorrect

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

for i in range(1, 6): The other options: for i in range(1, 5): will iterate over the numbers 1, 2, and 3 (up to, but not including 5). for i in [0, 1, 2, 3, 4, 5]: will iterate over the numbers 0 through 5 (inclusive), which is not from 1 to 5. for i in range(5): will iterate over the numbers 0 through 4 (up to, but not including 5), which also does not start at 1.

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

fruits[-5]

Which one is NOT a legal variable name in Python? my-var my_var Myvar _myvar

my-var

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

player1_username = "jackbauer"

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[7, 2]) print(arr[3, 0]) print(arr[1, 2])

print(arr[1, 2])

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

print(dict[1]) The line print(dict[1]) is incorrect because you are attempting to access the dictionary with the key 1, but the dictionary contains string keys ("a", "b", and "c"), not integer keys. Dictionary keys must match the type and value of the keys used when creating the dictionar The strings "a," "b," and "c" are indeed keys. In a Python dictionary, the keys are used to access the associated values. Each key is unique within the dictionary, and you can use these keys to look up or modify the values associated with them.

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]) print(order[main][2][0]) print(order["dessert" - 1][2][0]) print(order["main"][2][0])

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

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} starting_dictionary["c"] = 7 final_dictionary = starting_dictionary final_dictionary = starting_dictionary.append({"c": 7}) final_dictionary = starting_dictionary["c"] = 7 final_dictionary = starting_dictionary["c"]: 7

starting_dictionary["c"] = 7 final_dictionary = starting_dictionary

Which block of code will produce an error? 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")

time_until_Midnight - Should match time_until_midnight Capital M is an error

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

while and for


Conjuntos de estudio relacionados

Chapter 7 Arrays and Vectors Review Questions.

View Set

The Family: Chapter 2 the Family in History

View Set

Managerial Accounting, 4e (Whitecotton) Chapter 3 Process Costing

View Set