Python Final
Which is the correct syntax for opening a file in Python?
my_file = open('Wikipedia_data.txt')
The pyplot.axis() function is used to define the _____.
range of the axes
Which function returns a numeric output?
os.path.getsize()
If /Users/ABC/script.txt is the path to a file, which statement returns True as a value?
os.path.isfile('/Users/ABC/script.txt')
Which function is used to create a portable file path string by concatenating the strings using the correct path separator?
os.path.join()
In plt.plot(X, Y, color='ro-', linewidth=5, markersize=5, alpha=0.35), which property is defined by alpha?
transparency
Which XXX completes the find_smallest() function? def find_smallest(a, b, c): if a <= b and a <= c: smallest = a elif b <= a and b <= c: smallest = b elif c <= a and c <= b: smallest = c XXX result = find_smallest(7, 4, 8) print(result)
return smallest
Which function takes an optional format string argument to specify the color and style of the plotted line?
plt.plot()
Which function is used to add text labels to a plot?
plt.text()
Which is incorrect syntax for axvline() function?
plt.axvline(y, xmin, xmax, linewidth=1, color='r')
Which function plots data onto the graph?
plt.plot()
The Numbers.txt file contains a list of integer numbers. Complete the code to print the sum of the numbers in the file. f = open('Numbers.txt') lines = f.readlines() f.close() XXX print(sum)
sum = 0 for i in lines: sum += int(i)
It is recommended to use a 'with' statement when opening files so that ____.
the file is closed when no longer needed
What is output? new_list =[10, 20, 30, 40] for i in range(len(new_list)): if new_list[i] != new_list[-1]: new_list[i] *= 2 print(new_list)
[20, 40, 60, 40]
What is output? new_list = [223, 645, 500, 10, 22] new_list.sort() for i in new_list: ind = new_list.index(i) if ind > 0: new_list[ind-1] += i print(new_list)
[32, 245, 723, 1145, 645]
What is output? b1 = [7, 5, 9, 6] b1.sort() b2 = b1.copy() b1.append(10) b2 = b2[::-1] print(b1, b2)
[5, 6, 7, 9, 10] [9, 7, 6, 5]
What will be output for print(f'{1.6180339:.5f}')?
'1.61803'
Select the output generated by the following code: new_list = [10, 10, 20, 20, 30, 40] for i in range(3): print(new_list[i]) new_value = new_list.pop(0)
10 20 30
What is output? new_list = [0, 1, 2, 3, 4] print(all(new_list)) print(min(new_list) + max(new_list))
False 4
Which of the following is not a valid technique to create a function stub?
Leave the function body empty
If two variables with the same name exist in the Local scope and the Global scope, which variable will be used in an assignment statement?
The Local scope variable
Which correctly calls the add() function? def add(a, b, c): return a + b + c
add(2, 4, 6)
What statement replaces XXX, causing the program to print the word ' hello'? def print_hello():print('hello')XXXalternate()
alternate = print_hello
In the following code, the variable val is the function call's _____. def calc_square_area(size): area = size * size return area val = float(input('Enter size of square: ')) square_area = calc_square_area(val) print(f'A square of size {val} has area {square_area}')
argument
Which variable can be used in place of XXX in the following code? def fahrenheit_to_celsius(f):fraction = 5 / 9c = (f - 32) * fractionreturn cdegrees = float(input('Enter degrees in Fahrenheit: '))print(fahrenheit_to_celsius(XXX))
degrees
Which term describes how Python assigns the type of a variable?
dynamic typing
What code replaces XXX to make the program output the number 10? multiplier = 1 def do_multiplication(x): return x * multiplier def set_multiplier(x): XXX multiplier = x user_value = 5 set_multplier(2) print(do_multiplication(user_value))
global multiplier
What is output? my_list = ['hello', 'good', 'morning'] print(my_list[1][:3])
goo
Which property is required for plt.legend()?
label
A(n) _____ is an example of a mutable object type.
list
What is the output? def gen_command(application, **kwargs): command = application for key in kwargs:value = kwargs [key]command += f' --{key}={value}' return command print(gen_command('ls', color='always', sort='size', format='long'))
ls --color=always --sort=size --format=long
Choose the option that gives ['ABC', 'ABC'] as the output.
my_list = ['ABC', 'DEF'] my_list[len(my_list)-1] = 'ABC' print(my_list)
Choose the option that gives 'great' as the output.
my_list = ['books', 'are', 'great', 'for', 'learning'] my_list.sort()print(my_list.pop(3))
Which of the following methods will change the string 'Python Programming' into 'PYTHON PROGRAMMING'?
upper()
What is the value of new_title? title = 'Python for Beginners' tokens = title.split(' ') if 'Chapter 1' not in tokens: tokens.append('Chapter 1') new_title = ' '.join(tokens)
'Python for Beginners Chapter 1'
What is the output? def display(product, options=[]):if 'monitor' in product:options.append('HDMI')print(product, options)display('Acer monitor')display('Samsung monitor')
Acer monitor ['HDMI'] Samsung monitor ['HDMI', 'HDMI']
What is output? my_dict = {'AA':3, 'BB': 2, 'CC':1, 'DD':0} v1 = list(my_dict.keys())[list(my_dict.values()).index(1)] v2 = {v:k for k, v in my_dict.items()}[0] print(v1,v2)
CC DD
What is the output? def print_fever_check(temperature):NORMAL_TEMP = 98.6CUTOFF_TEMP = 95degrees_of_fever = 0if (temperature > NORMAL_TEMP):degrees_of_fever = temperature - NORMAL_TEMPprint(f'You have {degrees_of_fever:f} degrees of fever.') elif (temperature < CUTOFF_TEMP):degrees_of_fever = CUTOFF_TEMP - temperatureprint(f'Your temperature is {degrees_of_fever:f} below 95.') body_temperature = 96.0print('Checking for fever...')print_fever_check(body_temperature)
Checking for fever...
Which of the following statements is incorrect for python dictionaries?
Dictionaries cannot contain objects of arbitrary type
In Python, a namespace is which type of data structure?
Dictionary
_____ objects have fixed values that can't be changed.
Immutable
What is output? new_string = 'One giant leap for mankind' print(new_string[0:6])
One gi
Which symbols are used to start and end a docstring?
Three quotation marks (""")
What is output? my_list = [20, 25, 'hello'] new_list = my_list[:] print(new_list[0:2]) print(my_list[-1])
[20, 25] hello
How do you obtain a list of tuples of key-value pairs in a dictionary dict?
dict.items()
What defines the minimum number of characters that must be inserted into the string?
field width
In the following code, the variable size is the function's _____. def calc_square_area(size): area = size * size return area val = float(input('Enter size of square: ')) square_area = calc_square_area(val) print(f'A square of size {val} has area {square_area}')
parameter
Which uses the concat() function to output: red fish blue fish? def concat(*args):s = ''for item in args:s += ' ' + itemreturn s
print(concat('red', 'fish', 'blue', 'fish'))
Which function call will produce an error? def purchase(user_name, id_number=-1, item_name='None', quantity=0): # ... process a user's purchase as required ...
purchase(item_name='Orange', 10)
Which statement uses the square() function to assign the variable t with 16? Note that 16 = 2⁴ = (2²)² def calc_square(x):return x * x
t = calc_square(calc_square(2))
4 oval graphs
theta1 = np.linspace(0, np.pi, 100)r = 1plt.subplot(2, 2, 1)plt.plot(r*np.cos(theta1), r*np.sin(theta1))plt.subplot(2, 2, 2)plt.plot(r*np.cos(theta1), r*np.sin(theta1))plt.subplot(2, 2, 3)plt.plot(r*np.cos(theta1), r*np.sin(theta1))plt.subplot(2, 2, 4)plt.plot(r*np.cos(theta1), r*np.sin(theta1))plt.show()
Which of the following statements correctly opens a file in append mode without the need for specifying a close() function for the file?
with open('my_list.txt', 'a+') as file:
What is output? new_list = [10, 20, 30, 40] for i in new_list[:]: print(i) new_value = new_list.pop(0)
10 20 30 40
After the program runs, what is the value of y? def print_sum(num1, num2)print(num1 + num2)y = print_sum(4, 5)
9
What will be the date type for type(list_name.sort()) and type(sorted(list_name))?
< class 'NoneType'>, < class 'list'>
Which line in the function print_greeting() must be changed if the user wishes to print the greeting three times with three different names? def print_greeting(name):print('Welcome message:')print('Greetings', name)
None. To print the greeting with three different names, the main program must call print_greeting() three times with three different arguments.
What needs to be provided for the pyplot.subplot() function arguments?
Rows, columns, and active subplot
data.csv:Product Name, PricePen, 10Pencil, 20Eraser, 5 What is output? import csvwith open('data.csv','r+') as file:csvFile = csv.reader(file)for row in csvFile:print(row)
['Product Name', ' Price'] ['Pen', ' 10'] ['Pencil', ' 20'] ['Eraser', ' 5']
Consider the following my_script.py. What is the output when the command-line argument python my_script.py input.txt output.txt is run on the terminal? import sysprint(sys.argv)for i in sys.argv:if len(i) > 10:print(len(i))
['my_script.py', 'input.txt', 'output.txt'] 12
What is output? b1 = [7, 5, 9, 6] b1 = sorted(b1) b2 = b1 b2.append(2) print(b1, b2)
[5, 6, 7, 9, 2] [5, 6, 7, 9, 2]
What is output? b1 = [[7, 5, 9], [3, 2, 1]] b1.sort() b2 = b1[:] print(b1, b2) for elem in b2: elem.sort() print(b1, b2)
[[3, 2, 1], [7, 5, 9]] [[3, 2, 1], [7, 5, 9]] [[1, 2, 3], [5, 7, 9]] [[1, 2, 3], [5, 7, 9]]
Which of the following code blocks will print both keys and values?
dict1 = dict(number = 10, color = 'Red', word = 'Chair') for keys, values in dict1.items(): print(keys, values)
Which script writes 'Hello!' in the file sample.txt for the command line argument python myscript.py sample.txt Hello!?
f = open(sys.argv[2], 'w') f.write(sys.argv[3]) f.close()
Which statement causes the face with 'x' characters for eyes to be printed? def print_x_eyes(): print('x x') def print_o_eyes(): print('o o') def face(eyes): eyes() print(' > ') print('----')
face(print_x_eyes)
A comma separated values (csv) file is a simple text-based file format that uses commas to separate _____.
fields
Which statement opens a file for appending?
file = open('ABC.txt', 'a')
Identify the correct syntax used to write to a text file.
file = open('My_data.txt', 'w') file.write('This file contains data')
Complete the code to append the values in my_list to a file named my_data.txt with one value in each line. my_list = [10, 20, 30, 50]XXX
file = open('my_data.txt', 'a+')for i in my_list:file.write(str(i) + '\n')
Which statement opens a file in read-only binary mode?
files = open('my_file.txt', 'rb')
Which XXX will display one more than half of the smallest value of w1, w2, and w3? def find_min_value(a, b, c): if a <= b and a <= c: return a elif b <= a and b <=c: return b else: return c w1 = 7 w2 = 3 w3 = 12 y = XXX print(y)
find_min_value(w1, w2, w3)/2 + 1
Which of the following methods forces the output buffer to write to disk?
flush() only
Identify the loop that prints the names of the directories, subdirectories, and files in a path.
for dirname, subdirs, files in os.walk(path):print(dirname, subdirs, files)
After a function's last statement is executed, the program returns to the next line after the _____.
function call
The code that includes the keyword "def" is called a _____.
function definition
What is the value of rgb_a? colors = {1: 'red', 2: 'green', 3: 'blue', 4: 'yellow'}popped_item = colors.pop(4)colors.update({ 4: 'alpha'})rgb_a = {}rgb_a['items'] = colors
{ 'items': { 1: 'red', 2: 'green', 3: 'blue', 4: 'alpha'}}
What is output? dict1 = {1: 'Hi', 2: 'Bye'}dict2 = {2: 'Yes'}dict1.update(dict2)dict3 = {3: 'No'}dict1.update(dict3)print(dict1)
{1: 'Hi', 2: 'Yes', 3: 'No'}
What is output? objects = {}objects['a'] = 'Chair'objects['b'] = 'Table'objects['c'] = 'Sofa'objects.clear()print(objects)
{}
Which line of the function has an error? def compute_sum_of_squares(num1, num2): # Line 1 sum = (num1 * num1) + (num2 * num2) # Line 2 return # Line 3
Line 3
What is the output? def print_message1(): print('Message #1') def print_message2(): print('Message #2') print_message1 = print_message2 print_message2 = print_message1 print_message1() print_message2()
Message #2 Message #2
What is output? new_string = 'Python' print(new_string[0:-1:2])
Pto
What is output? my_string = 'The area postal code is 99501' print(my_string[-5:].isdigit()) print(my_string[:3].isupper()) print(my_string[:3].islower())
True False False
What is the error? cone_vol = cone_volume(2, 4) print(cone_vol) def compute_square(r): return r * rdef cone_volume(r, h): return (0.33) * 3.14 * compute_square(r) * h
Undefined function cone_volume()
What is output? dict = {1: 'X', 2: 'Y', 3: 'Z'}print(dict.get(2, 'A'))
Y
Select the format string used to style the lines as shown in the image. red and blue parabolas with red + and blue -
r+ and b-
Given the following function. To change the function to return the product instead of the sum, how many lines of code need to be changed? def calculate(a, b):return a + bprint(calculate(3, 4))print(calculate(5, 2))print(calculate(6, 7))
3
For print(f'{"Mike":XXX}{1:YYY}'), which XXX and YYY will generate 'Mike=1' as the value of format_print?
*>4, =>2
Which X and Y cause the program to print the final velocity in feet per second? Note that the distance and initial_velocity are given using meters instead of feet. def final_velocity(initial_velocity, distance, time): return 2 * distance / time - initial_velocitydef meters_to_feet(distance_in_meters): return 3.28084 * distance_in_meters # display final velocity in feet per second t = 35 # seconds d = 7.2 # meters v_i = 4.6 # meters / second print(f'Final velocity: {final_velocity(X, Y, t):f} feet/s')
. X = v_i, Y = meters_to_feet(d)
What isoutput? def calc(num1, num2): return 1 + num1 + num2 print(calc(4, 5), calc(1, 2))
10 4
What is the output? def find_sqr(a): t = a * a return t square = find_sqr(10) print(square)
100
What is the output? LB_PER_KG = 2.2 def kgs_to_lbs(kilograms): pounds = kilograms * LB_PER_KG return pounds pounds = kgs_to_lbs(10) print(pounds)
22
What is output? my_books = 'Books 105' index = my_books.find('',3) print(index)
3
What XXX and YYY will left align the column values print(f'{"Product":XXX}{"Price(cash)":YYY}') print('-' * 24) print(f'{"Banana":XXX}{1.02:YYY}') print(f'{"Apple":XXX}{5.08:YYY}')
<16, <8
Standard Python functions such as int(), range() etc. are part of the _____ scope.
Built-in
What is output? my_string = 'Greetings!' print(my_string == 'greetings!') print('tin' in my_string) print('Hello' > my_string)
False True True
ABC.txt: Hello Hi GreetingsWhat is output? file = open('ABC.txt')lines = file.readlines()[2]print(lines)
Hello Hi
Which of the following is not one of the main scopes that Python uses to manage namespaces?
Namespace scope
What is the output? def is_even(num): if num % 2 == 0: even = True else: even = False is_even(7) print(even)
No output: An error occurs due to unknown variable even
What is output? new_string = 'Python' my_index = 0 while my_index != len(new_string)/2: print(new_string[my_index:int(len(new_string)/2)]) my_index += 1
Pyt yt t
What is output? my_poem = 'Roses are red; Violets are blue' new_separator = '.' new_poem = my_poem.split(';') print(new_separator.join(new_poem))
Roses are red. Violets are blue
What is output? my_string = 'What is your name?' print(my_string.split('?'))
['What is your name', '']
What is output? new_list = ['python', 'development'] new_list.append('in progress') print(new_list)
['python', 'development', 'in progress']
What is output? my_var = ['python'] my_list = my_var[0].split() my_list += 'world' del my_list[1] print(my_list)
['python', 'o', 'r', 'l', 'd']
What is output? new_list = [['hello', 'word'], 'good morning', 'have a nice day'] print(new_list[0:2])
[['hello', 'word'], 'good morning']
What is the output? def reset(data): data = [] print(data, end=' ') data = [15, 0, 47, 12, 0] reset(data) print(data)
[] [15, 0, 47, 12, 0]
Complete the following code to print the average of the list. new_list = [0, 1, 2, 3, 4] XXX print(f'The average is {avg}')
avg = sum(new_list)/len(new_list)
Which statement would replace XXX so that the output is: 4, 12, 30? def get_stats(int_list):result_sum = 0result_min = int_list[0]result_max = int_list[0]for value in int_list:result_sum += valueif value < result_min:result_min = valueif value > result_max:result_max = valuereturn result_sum, result_min, result_maxvalues = [ 6, 4, 12, 8 ]XXXprint(f'{a}, {b}, {c}')
c, a, b = get_stats(values)
Consider the list my_list = ['www', 'python', 'org']. Choose the option that returns 'www.python.org' as the value to my_string.
my_string = ('.').join(my_list)
Which function gives the change in temperature for an object, given the heat transfer, mass and specific heat capacity? Note that Q = m c Δ T , where Q is heat transfer, m is mass, c is specific heat capacity, and Δ T is the change in temperature.
def temperature_change(q, m, c): return q / (m * c)
Consider my_string = 'roy came third in the running race'. Which option will return 'Roy came 3rd in the running race' as the value of new_string?
new_string = my_string.capitalize() new_string = new_string.replace('thi', '3')
Consider the string new_string = 'Berlin is the capital of Germany'. Which statement will return 'capital of Germany' as a substring?
new_string[-18:]
Consider the string new_string = 'Code development in Python'. Which statement will return 'velop' as a substring?
new_string[-19:12]
Select the line of code which is a 2-D array.
np.array([1, 2, 3, 4, 5],[6, 7, 8, 9, 10])
The process of searching namespaces for a name is called _____.
scope resolution
Complete the code to plot Salary=[5,6,7,8] and Grade=[100,200,300,400]. import numpy as npimport matplotlib.pyplot as pltXXX
plt.plot(Salary,Grade)plt.show()
Identify the correct syntax for text() function to display 'X Y Plot' at the coordinates (x,y) in grey color and font size 12.
plt.text(x,y, 'X Y Plot', color='grey', fontsize=12)
What is output? mydict = {x: x*x for x in range(0, 5)}for data in mydict.values():print(data, end=' ')
0 1 4 9 16
What is the result when the program is executed? def add(x, y):return x + yprint('Begin test')s = add('hello', 5)print(s)print('End test')
The program outputs 'Begin test', then an error is generated, and the program exits.
How does the given function improve the code versus if no function was present? def fahrenheit_to_celsius(fahrenheit):return (fahrenheit - 32.0) * 5.0 / 9.0fahrenheit = float(input())c1 = fahrenheit_to_celsius(fahrenheit);c2 = fahrenheit_to_celsius(32.0);c3 = fahrenheit_to_celsius(72.0);
The use of the function decreases redundant code
Which of the following is not a reason to use functions?
To make the code run faster
Which of the following types of constructs should be called when the programmer wants to stop program execution?
Use a pass statement
Which syntax creates a sequence of bytes by encoding the string using ASCII?
bytes('A text string', 'ascii')
Which of the following functions creates a sequence of 50 bytes?
bytes(50)
Which of the following lines of code is not valid, given the definitions of the calc_cube() and display() functions? def calc_cube(x):return x * x * xdef display(x):print(x)
calc_cube(x) = 8.0
The with statement creates a(n) _____ which performs setup and teardown operations.
context manager
The _____ function is used to create a second axis on a plot.
twinx()
What is the value of pathsplit? import osdir_path = '/Users/ABC/script.txt'pathsplit = os.path.split(dir_path)
('/Users/ABC', 'script.txt')
Which of the following is an advantage of using function stubs?
Helps with incremental programming
Which statement converts a sequence of bytes called my_bytes into a 4-byte integer?
val = struct.unpack('>l', my_bytes)
Which of the following statements prints the last field in each row of the csv file?
with open('my_file.csv', 'r') as f: csv_data = csv.reader(f) for r in csv_data: print(r[-1])
Which code opens a csv file with semicolon as a delimiter?
with open('my_file.csv', 'r') as file:csv_data = csv.reader(file, delimiter = ';')
my_list.txt: 150+250 Which of the following code blocks writes the sum in a new line of the file?
with open('my_list.txt', 'r+') as file: line = file.readline() sum = 0 for i in line.split('+'): sum = sum + int(i) file.write(str(sum))
What does np.ones((3, 2)) create?
[[1. 1.] [1. 1.] [1. 1.]]
Identify the (x[2], y[2]) coordinate in the following code. import matplotlib.pyplot as plt Salary=[10,20,30,40,50] Grade=[1,2,3,4,5] plt.plot(Salary,Grade) plt.title('Salary vs Grade') plt.xlabel('Salary') plt.ylabel('Grade') plt.show()
(30, 3)
What is output? dict1 = {}dict1['a'] = 4dict1['b'] = 5dict1['c'] = 2dict1['d'] = 1dict1['e'] = 3 mylist = list(dict1.values())sorted_mylist = sorted(mylist)for x in sorted_mylist:print(x, end=' ')
1 2 3 4 5
What is a valid output? dict1 = {}dict1['Kilometer'] = 'Meter'dict1['Litre'] = 'Millilitre'dict1['Kilojoule'] = 'Joule'dict1['Ton'] = 'Kilograms'dict3 = {}for keys, values in dict1.items():dict3[keys] = values val = dict3.pop('Ton')for keys, values in dict3.items():print(f'{1} {keys} = {1000} {values}', end=' ')print('or', end=' ')print('1', keys, 'is equal to 1000', dict3[keys])
1 Kilometer = 1000 Meter or 1 Kilometer is equal to 1000 Meter 1 Litre = 1000 Millilitre or 1 Litre is equal to 1000 Millilitre 1 Kilojoule = 1000 Joule or 1 Kilojoule is equal to 1000 Joule
For the given program, how many print statements will execute? def print_shipping_charge(item_weight):if (item_weight > 0.0) and (item_weight <= 10.0): print(item_weight * 0.75)elif (item_weight > 10.0) and (item_weight <= 15.0):print(item_weight * 0.85)elif (item_weight > 15.0) and (item_weight <= 20.0):print(item_weight * 0.95)print_shipping_charge(18)print_shipping_charge(6)print_shipping_charge(25)
2
What is the length of the dictionary my_dict = {'Country':'India', 'State': {'City':'Delhi', 'Temperature':40}}?
2
What is output? new_list = [10, 20, 30, 40, 50] for i in new_list: print(i * 2)
20 40 60 80 100
Which of the following is true?
A function can have any number of return statements, or no return statement at all.
What is the output? def print_app(app_id, plan='basic', term=30):print(f'App:{app_id} ({plan} plan, {term} days)')print_app(10032, term=14)
App:10032 (basic plan, 14 days)
Which statement is true about the *args and **kwargs special arguments?
Both may be used in a single function call, but *args must appear before **kwargs in the argument list
Function calc_sum() was copied and modified to form the new function calc_product(). Which line of the new function contains an error? def calc_sum(a, b): s = a + b return s def calc_product(a, b): # Line 1 p = a * b # Line 2 return s # Line 3
Line 3
What is the output? def print_water_temp_for_coffee(temp): if temp < 195: print('Too cold.') elif (temp >= 195) and (temp <= 205): print('Perfect temperature.') elif (temp > 205): print('Too hot.') print_water_temp_for_coffee(205) print_water_temp_for_coffee(190)
Perfect temperature. Too cold.
_____ allows a function or operator to perform different tasks depending on the types of the arguments or operands.
Polymorphism
Which is the correct location to place a docstring for a function?
The first line in the function body
What is output? new_list = [10, 'ABC', '123', 25] my_list = new_list[:] new_list[2] = 16 print(new_list) print(my_list)
[10, 'ABC', 16, 25] [10, 'ABC', '123', 25]
Complete the following code to get 'Email me at [email protected] or call at 333 222 1111' as output. email = 'Email: [email protected]' phone = 'Ph: 333-222-1111' print(f"Email me at {XXX} or call at {YYY}")
XXX: email.split(' ')[1], YYY: ' '.join((phone.split(': ' )[1]).split('-'))
What is the output? def modify(names, score): names.append('Robert') score = score + 20 players = ['James', 'Tanya', 'Roxanne'] score = 150 modify(players, score) print(players, score)
['James', 'Tanya', 'Roxanne', 'Robert'] 150
Which of the following code blocks will give 3 as the output?
my_list = [10, 10, 2, 5, 10] print(my_list.index(10) + my_list.count(10))
Choose the correct syntax to complete the code below in order to print [1, 2, 3, 4, 5] as the output. my_list = [3, 2, 5] XXX print(my_list)
my_list.extend([1, 4]) my_list.sort()
Which function is most appropriate to improve the given code? power_consumption_app1 = 600.85hours_of_use1 = 12.8energy_per_day1 = (power_consumption_app1 * hours_of_use1) / 1000power_consumption_app2 = 1800.45hours_of_use2 = 0.45energy_per_day2 = (power_consumption_app2 * hours_of_use2) / 1000power_consumption_app3 = 70hours_of_use3 = 1.5energy_per_day3 = (power_consumption_app3 * hours_of_use3) / 1000total_energy_consumed = energy_per_day1 + energy_per_day2 + energy_per_day3print(f'The total energy consumed per day is {total_energy_consumed:f}')
def compute_energy_consumed(power, hours): return (power * hours) / 1000
Which of the following options can sort the list in descending order? i. list_name.sort(reverse=True) ii. sorted(list_name, reverse=True) iii. sorted(list_name)[::-1] iv. sorted(list_name)
i, ii, iii
Consider the following my_script.py. Which statement should replace XXX in the script for the command-line argument python my_script.py input.txt? import sysimport osif len(sys.argv) != 2:print('Usage: {} inputfile '.format(sys.argv[0]))sys.exit(1)print('Opening file {}...'.format(sys.argv[1]))XXXprint('Oh No! The file does not exist.')sys.exit(1)
if not os.path.exists(sys.argv[1]):
memberDetails.txt: Name: Ben Age: 50Which XXX will read the file and print 'Ben'? file = open('memberDetails.txt')XXXfile.close()
line = file.readline()[6:] print(line)
What is output? import matplotlib.pyplot as pltSalary=[x*x for x in range(-70,70,1)]Grade=[x for x in range(-70,70,1)]plt.plot(Grade,Salary,'c-')plt.title('X vs Y')plt.xlabel('X')plt.ylabel('Y')plt.show()
linear starting at -60
Which package is used for plotting in Python?
matplotlib
Select the code that gives ['cat in a hat', 'fluffy dogs', 1989, 1990] as the output.
new_list = ['1000', '2000', '3000', 'cat in a hat', 'fluffy dogs'] print(new_list[-2:] + [1989, 1990])
Which of the following code blocks produces the output given below?['odd', 'even', 'odd', 'even']
new_list = [3, 4, 5, 6] for i in range(len(new_list)): if new_list[i] % 2 == 0: new_list[i] = 'even' else: new_list[i] = 'odd' print(new_list)
Identify the code used for matrix multiplication of two arrays.
np.dot(array1, array2)
Which numpy function creates the sequence [0.4,0.5,0.6,0.7]?
np.linspace(0.4,0.7,4)
Which package provides tools for scientific and mathematical computations in Python?
numpy
Identify the error in the program given below. my_dict = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5}_popped = my_dict.pop('B', 6)print('Value popped: ' + str(_popped))my_dict['F'] = 0_popped = my_dict.pop('F', 0)_popped = my_dict.pop('B')print('Value popped: ' + str(_popped))
my_dict.pop('B') causes error
Select the option to get the value of temperature from the dictionary my_dict = {'Country':'India', 'State': {'City':'Delhi', 'Temperature':40}}
my_dict['State']['Temperature']
Which of the following statements reads up to 100 bytes from a file named student.txt?
my_file = open('student.txt') line = my_file.read(100)
What is the value of sys.argv[2] in the command-line argument python run_my_file.py input.txt output.csv save_error?
output.csv
Identify the correct syntax to annotate the data point at (5,2) placing the text 'Peak' at (5,3).
plt.annotate('Peak', xy=(5, 2), xytext=(5, 3))
Which statement defines a red X marker of size 5 and line width 10 for a line plot?
plt.plot(X, Y, 'rX', linewidth=10, markersize=5)
The letter e has a hexadecimal value of 0x65. Which of the following statements prints the bytes literal value 'e'?
print(b'\x65')
Choose the print statement that generates ['a', 'd'] as the output for my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(my_list[0:-1:3])
Consider the list my_list = [1880, '990EZ', 'Tax Forms']. Which statement gives '990EZ' as the output?
print(my_list[1])
Which XXX causes the program to output the message "Hello!"? def print_message(): print('Hello!') XXX
print_message()
Which function call would cause an error? def print_product(product_name, product_id, cost): print(f'{product_name} (id: #{product_id}) - ${cost:.2f}')
print_product('Speakers', 32.99, 21224)
Which XXX is used to write data in the file? import csvrow1 = ['1', '2', '3']row2 = ['Tina', 'Rita', 'Harry']XXXstudents_writer = csv.writer(csvfile)students_writer.writerow(row1)students_writer.writerow(row2)students_writer.writerows([row1, row2])
with open('students.csv', 'w') as csvfile:
Which choice is not a valid call of the get_random_pair() method? def get_random_pair():a = random.randint(0, 100)b = random.randint(0, 100)return a, b
x y = get_random_pair()
Which XXX is valid for the following code? def calc_sum(a, b): return a + b XXX print(y)
y = calc_sum(4, 5)
If factor = 24, which format will generate '**24', right aligned in its field?
{factor:*>4}