Python Final

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is output? objects = {}objects['a'] = "Chair"objects['b'] = "Table"objects['c'] = "Sofa"objects.clear()print(objects)

[]

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)

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]

Add a print statement to the function definition to print the hours, given minutes. There are 60 minutes in one hour. def print_minutes_as_hours(original_minutes): ... minutes = float(input()) print_minutes_as_hours(minutes)

print(original_minutes / 60)

Which of the following statements returns '< class 'list'>, 5' as the output for the command-line input > python prog.py 1 January 2020 ?

print(type(sys.argv), int(sys.argv[1])+len(sys.argv))

Add a return statement to the function definition that returns the result of adding num1 and num2. def sum(num1, num2):

return num1 + num2

What is the value of sys.argv[1]+len(sys.argv[1]) for the command-line input > python prog.py 121 ?

runtime error

Match the words

scope resolution: The process of searching namespaces for a name. namespace: Maps the visible names in a scope to objects. locals(): Returns a dictionary of the names found in the local namespace. scope: The area of code where a name is visible.

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'

Which XXX will generate Mike=1 as the value of format_print ? format_print = XXX.format(name='Mike', score=1)

'{name:*>4}{score:=>2}'

What is the value of pathsplit ? import osdir_path = '/Users/ABC/script.txt'pathsplit = os.path.split(dir_path)

('/Users/ABC', 'script.txt')

What is the Big O notation of the function f(x) = 3 + 4 * N + 5 * N^3?

0(N^3)

Which function best represents the worst-case scenario for the following loop? count = 0while i > 0:i = i / 2count += 1

1 + logv2 N * 3

Given the list [20, 10, 19, 90], i = 0, and k = 3, what are the contents of the low partition? Assume quicksort always chooses the smallest element as the pivot.

10

A list of 5,000 players of a team needs to be searched for the player with the highest score. What is the fastest possible runtime for linear searching this list assuming each comparison takes 2 µs?

10000

If a list has 20 elements, how many outer loop iterations are executed for selection sort?

19

What is the output? new_list = [10, 20, 30, 40, 50]for i in new_list:print(i * 2)

20 40 60 80 100

How long will the insertion sort algorithm take to sort a list of 8 elements if each comparison takes 1μs?

28μs

In [2, 3, 6, 10, 20, 25, 100], how many elements will be checked to find the element 20 using binary search?

3

What is output? my_books = 'Books 105'index = my_books.find('',3)print(index)

3

What is output? my_list = [200, 6, 11, 3, 90, 3.3]num_to_find = 10 // 3count = 0for i in my_list:if i == num_to_find:print(count)count += 1

3

Identify the pivot value for the numbers [0, 2, 4, 7, 92], i = 0, k = 4.

4

What is output? my_list = [20.0, 6, 11, 3, 90, 3.3]my_list.sort()first = 0last = len(my_list) - 1count = 0num_to_find = 100//5while last >= first:mid = (first + last) // 2count += 1if my_list[mid] < num_to_find:first = mid + 1elif my_list[mid] > num_to_find:last = mid - 1else:print(mid,count)break

4 2

Assume a function def print_num(user_num): simply prints the value of user_num without any space or newline. What will the following code output? print_num(43) print_num(21)

4321

Given a function definition: def calc_val(a, b, c): what value is assigned to b during this function call? calc_val(42, 55, 77)

55

Given a list of 64 elements, how many elements will be checked to look for a value that is larger than the largest value in the list using binary search?

7

Given the list ['cats', 'turtles', 'dogs', 'birds', 'snakes'], how many total comparisons will insertion sort require?

8

Which of the following statements is true for built-in exceptions?

A built-in exception can be called in a code using a 'raise' statement.

A programmer will typically write a Script and pass it to the interpreter.

A module object is a namespace that contains definitions from the module.

Which of following modules would warrant the use of the reload() function in a script?

A module that scrapes off data from a list of websites which are updated every day.

The reload() function returns the namespace of the module with updated definitions

A package is a directory that gives access to all of the modules stored in a directory when imported.

What is the difference between an argument and a parameter?

A parameter is a function input specified in a function definition, whereas an argument is a value provided to a function's parameter during a function call.

Python uses exception-handling constructs to handle errors during execution.

A python code only runs the except block when an error occurs in the preceding try block

A comma separated values (csv) file is a simple text-based file format that uses commas to separate fields

A(n) algorithm is a sequence of steps for accomplishing a task.

Linear search is a search algorithm that sorts the list from the start of a list and checks each element until the search key is found

All functions that have the same growth rate are considered equivalent in Big O notation.

In which scenario can a binary search be used to find an element?

An alphabetical list of employee names

What is the 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 output? def print_number(a):try:print('{0:.2f}'.format(a))except:print('Cannot print the value')print_number('10')print_number(2.0)

Cannot print the value 2.00

Which of the following statements is incorrect for python dictionaries?

Dictionaries cannot contain objects of arbitrary type

What is output? def get_name(name):if len(name) <= 2:raise ValueError('You need to enter your complete name.')return namedef get_age(age):if age > 100:raise ValueError('Please enter some value')return agetry:name = get_name('Mike')school_name = get_age('3')print('{} is {} years old.'.format(name, school_name))except ValueError as excpt:print(excpt)except:print('Error!')

Error!

Is the following a valid function definition beginning? def my_fct(userNum + 5):

False

What is the output? new_list = [0, 1, 2, 3, 4]print(all(new_list))print(min(new_list) + max(new_list))

False 4

What is output? my_string = 'Greetings!'print(my_string == 'greetings!')print('tin' in my_string)print('Hello' > my_string)

False True True

What is output for a file ABC.txt that contains the following: HelloHiGreetings file = open('ABC.txt')lines = file.readlines()[2]print(lines)

Greetings

PYTHONPATH can be set to specify optional directories where modules are located.

If __name__ == "__main__" is true, then the file is being executed as a script

Which of the following statements is not true for importing a module:

If the module has already been loaded, then a new namespace is created and its codes are executed.

What is output? def division(a, b):try:div = a / bprint("Quotient: {}".format(div))except (TypeError, ZeroDivisionError):print("Invalid Input!")except (ValueError):print("Invalid Input Value!")division(2, 0)division('2', 10)division(36.0, 5.0)

Invalid Input! Invalid Input! Quotient: 7.2

What is output? time = 0distance = 0try:if time <= 0:raise ValueError('Invalid Time!')if distance <= 0:raise ValueError('Speed: 0')speed = distance / timeprint('Speed: {}'.format(speed))except ValueError as expt:print(expt)print('Cannot calculate speed.')

Invalid Time! Cannot calculate speed.

What is output? def odd_even(a):if isinstance(a, int):if a % 2 == 0:return 'even'else:return 'odd'else:raise TypeError("Invalid Variable Type!") try:n = '3'print(odd_even(n))except TypeError as expt:print(expt)except:print("Error!")finally:print('Value entered:', n)

Invalid Variable Type! Value entered: 3

Which of the following is true for an environment variable?

It can be accessed by every program running on the computer

The with statement creates a context manager which performs setup and teardown operations.

It is recommended to use a 'with' statement when opening files so that the file is closed when no longer needed

What are the values of sys.argv[1] and type(sys.argv[2]) for the command-line input > python prog.py June 16 ?

June, <class 'str'>

During the merge sort operation for the list [89, 6, 8, 42, 60, 9, 20, 34], at what left and right partition position is 20 added to the temporary list?

Left position is 2 and right position is 5

Merge Sort is a sorting algorithm that divides a list into two halves, recursively sorts each half, and then merges the sorted halves to produce a sorted list.

Merge Sort

What is the output if the input is 0? class MyDivideByZeroError(Exception):def __init__(self, value):self.value = valueException.__init__(self, value)print('Enter a number\n')num = int(input())try:if num == 0:raise MyDivideByZeroError('Number needs to be greater than zero!\n')exitelse:num = num / 0print('Your number after dividing by zero: ', my_num)except MyDivideByZeroError:print('My Exception raised')except:print('Oops! An unknown error occurred.\n')

My Exception raised

How many comparisons are needed for elements of a list of size N already in sorted order?

N-1

Which of the following functions will have the biggest growth rate?

N^2

What is the complexity of the following loop? for i in range(N):for j in range(N-5):new_val = i + j

O (N^2)

What is the complexity of the loop? for i in range(10):if i < 5:print(i, 'is less than 5')if i == 5:print(i, 'is equal to 5')if i>5: print(i, 'is greater than 5', i)

O(1)

What is the worst-case runtime for a merge sort?

O(N logN)

What is the runtime complexity of selection sort?

O(N^2)

What is the simplified big O notation for the following function?3N^2 * O(N)

O(N^3)

What is the Big O notation for the worst-case runtime for the following code? i = 1while(i < number)if i >= 1:i = i * 2

O(logN)

Which of the following is added into the global namespace after running the from ABC import (length, breadth) import statement?

Only the length and breadth attributes of ABC.

Which is true for a quicksort algorithm?

Quicksort algorithm's runtime is typically O(N log N).

Insert Sort is an algorithm that treats a list as two parts, a sorted part and an unsorted part, and repeatedly inserts the next value from the unsorted part into the correct location in the sorted part

Quicksort is a sorting algorithm that repeatedly partitions the input into low and high parts (each part unsorted), and then recursively sorts each of those parts.

Complete the binary search function. def binarySearch (array, first, last, key): if last >= first: mid = int(first + (last - first)/2)if array[mid] == key: return mid elif array[mid] > key: ##Statement 1else: ##Statement 2else: return -1

Statement 1: return binarySearch(array, first, mid-1, key) Statement 2: return binarySearch(array, mid+1, last, key)

A tuple should be used to specify all the exception types when being handled by a single exception handler.

The as keyword binds a name to the exception being handled.

Which of the following directories is contained in sys.path ?

The directory where Python is installed.

What happens when an unhandled exception occurs?

The finally clause executes and then the exception is re-raised.

What happens when a raise statement is encountered in a function?

The function is exited with no return.

Which of the following statements is the reason for avoiding the use of a catch-all except clause?

To make sure that no bug is hidden under the catch-all except block

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 output? dict = {1: "X", 2: "Y", 3: "Z"}print(dict.get(2, "A"))

Y

What will ['Alaska', 'New York', 'Washington', 'Oregon', 'Florida'] be after completing the third outer loop for insertion sort?

['Alaska', 'New York', 'Oregon', 'Washington', 'Florida']

Consider the csv file data.csv containing the following details. What is output? Product Name, PricePen, 10Pencil, 20Eraser, 5 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']

What is the output? my_list = [['cat in a hat'], ['Dr', 'Seuss']]print(my_list[1][1:])

['Seuss']

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

Which of the following lists are sorted in ascending order?

[123, 12, 11.2, 9, 3.2, 2.09]

Which statement is true?

[20, 19, 8, 6, 0] is sorted in descending order.

In the list [100, 90, 32, 9, 3, 35, 10, 98], what will the list be after completing 4 outer loop iterations?

[3, 9, 10, 32, 100, 35, 90, 98]

Given [0, 2, 4, 7, 92], i = 0, k = 4, what are the contents of the right partition?

[7, 92]

Given [20, 10, 19, 90, 11, 12], i = 3, and k = 5, what are the contents of the left partition?

[90, 11]

Which list is sorted in descending order?

[Sanctuary, Park, Library, Beach, Aquarium]

What is output? from math import (pi, exp, log)import urllibprint(__name__)

__main__

Which could be the name of the function for the import statement from Shapes.Square.dimensions import area? Shapes

area

Which of the following algorithms has a logarithmic runtime complexity?

binary search

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 statements provides the path to a module named circle.py?

circle.__file__

Which of the following is a good example of the definition of a custom exception type?

class InputError(Exception): def __init__(self, value): self.value = value

Which XXX is the correct example for defining a custom exception? XXXtry:f = "Myfile.txt"ext = f.split('.').pop()if (ext == "txt"):raise InvalidFileTypeError('Invalid File Type')except Exception as e:print(e)finally:print('All done!')

class InvalidFileTypeError(Exception): def __init__(self, value): self.value = value

Write a function definition that returns one-half the value of its one parameter. Your Answer: def half(user_input): return user_input / 2 user_input = int(input()) print(half(user_input))

def half(a_number): return a_number / 2

Which of the following is an example of O(N), Linear notation?

def linear_search(numbers, key): for i in range(len(numbers)): if numbers[i] == key: return i return -1 # not found

Fill in the blank to complete the function definition to have a parameter named user_age. def print_age(___):

def print_age(user_age):

How do you obtain a list of tuples of key-value pairs in a dictionary dict ?

dict.items()

Which of the following is the correct syntax for a multiple exception handler?

except (NameError, AttributeError):

Complete the code to handle the exception and to print Error Occurred. new_string = 'Python'my_index = 0try:while my_index != len(new_string)/2:print(new_string[my_index:len(new_string)/2])my_index += l##fill the code here##print("Error Occurred")

except (NameError, TypeError):

Which of the following statements causes a ValueError to occur?

except ValueError

Which XXX generates the following output? Division by zero100503325 my_list = [0, 1, 2, 3, 4]for i in my_list:try:if i == 0:raise ZeroDivisionError('Division by zero')else:num = 100 // iprint(num)XXX

except ZeroDivisionError as e:print(e)

Which script writes Hello! in the file sample.txt for the command line argument python myscript.py sample.txt Hello!?

f = open(sys.argv[1], 'a')f.write(sys.argv[2])f.close()

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]#Fill the code here##

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 of the following methods forces the output buffer to write to disk? append()

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)

Identify the code that sorts the numbers in descending order. def selection_sort(numbers):for i in range(len(numbers) - 1):index = i# Missing code temp = numbers[i]numbers[i] = numbers[index]numbers[index] = temp

for j in range(i + 1, len(numbers)): if numbers[j] > numbers[index]: index = j

Consider a module file named Rectangle containing functions calc_area() and length(). Which option is the right way to import only these functions?

from Rectangle import (calc_area, length) print(calc_area(5, 10))

Identify the code that generates 'The value of pi is: 3.14' as output.

from math import pi print('The value of pi is: {0:.2f}'.format(pi))

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]):

Which of the following statements imports an entire module named ABC ?

import ABC

Identify the correct package import statement for print("Area = {}" .format(Shapes.Square.dimensions.area(a))).

import Shapes

Consider a package Shapes that contains the modules square.py, rectangle.py, and circle.py. Which of the following statements should be used to import rectangle.py?

import Shapes.rectangle

Identify the correct import statement for the following code: print('The sum of values is: {}'.format(calculate.sum(10, 20)))

import calculate

Identify the module file circle.py for the given code that will generate the following output. Radius is 6Area: 113.10 from circle import (area, radius)if __name__ == "__main__":a = area(6)print("Area: {0:.2f}".format(a))

import math def area(r): print(radius(r)) return math.pi * r * r def radius(r): return('Radius is {}'.format(r)) if __name__ == "__main__": print(radius, area)

Identify the code that generates os as output.

import os print(os.__name__)

Identify the correct syntax for importing modules from the script readFile.py?

import readFile

Which of the following statements pauses code execution for 5 seconds?

import time time.sleep(5)

If the module urllib has not been loaded, which of the following statements causes the new module object to be created and added to sys.modules ?

import urllib

A custom exception type is usually defined by:

inheriting from the exception class.

Consider students = {"Semester_1" : {"Ryan":20, "Mercy":25}, "Semester_2" : {"Justin":21, "Andrea":26}} . What command should be used to obtain the count of entries?

len(students)

memberDetails.txt file contains the following. Complete the code to print Ben. Name: BenAge: 50 file = open('memberDetails.txt')##Fill in the code herefile.close()

line = file.readline()[6:] print(line)

Identify the function that handles the exception. def divide(a, b): return (a / b) def add(a, b): return (a + b) def multiply(a, b): return (a * b) def main(): a = 200.0 b = 0.0 try: add(a, b) divide(a, b) multiply(a, b) except: print('Error Occurred') main()

main()

Replace x and y with the correct module to generate the following output. Calculation done on: *actual date*36.0 from x import powimport ytoday_date = y.date.today()base = 6exponent = 2print("Calculation done on:", today_date)print(pow(base, exponent))

math, datetime

What is the output of the following program? def dog(): print('woof') def cow(): print('moo') dog = cow dog()

moo

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 is the correct syntax for opening a file in Python?

my_file = open('Wikipedia_data.txt')

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)

Choose the option that gives ['ABC', 'ABC'] as the output.

my_list = ['ABC', 'DEF'] my_list[len(my_list)-1] = 'ABC' print(my_list)

Which of the following library is used to retrieve the current working directory?

os

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

What is the value of sys.argv[2] in the python run_my_file.py input.txt output.csv save_error command-line argument?

output.csv

The letter e has a hexadecimal value of 0x65. Which of the following codes 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])

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'my_str = 'Email me at {} or call at {}'##fill the code here##

print(my_str.format(email.split(' ')[1], ' '.join((phone.split(': ' )[1]).split('-'))))

Which code generates 66 was found at position 4 as the output?

random_numbers = [2, 23, 45, 66, 77, 90] num1 = 99 num2 = 66 count = 1 for i in random_numbers: if i == num1 or i == num2: print('{} was found at position {}'.format(i, count))count += 1

For a function print_names imported in a code, which of the following statement is the correct syntax to reload that function in the same code?

reload(print_names)

The challenge of sorting is that a program cannot

see the entire list to know where to move an element

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()##Fill the code here##print(sum)

sum = 0 for i in lines: sum += int(i)

Which of the following standard libraries can be used to convert time zones?

time

Complete the code to generate Remainder: 0.0 as output. def Remainder(a, b):if b == 0:return(b%a)else:return(a%b)## fill the code here##finally:print('Remainder:', z)

try: a = 20 b = 0 z = Remainder(a, b) except: print('Wrong value entered')

Choose the code that produces Thank you! as output.

try:n = 0for i in range(n):print("Square of {} is {}".format(i,i*i))except:print('Wrong value!')finally:print('Thank you!')

Which XXX generates Error Occurred as the output? def larger(a, b=1):if a > b:return aelse:return bXXXexcept:print("Error Occurred")

try:print(larger('21', 33))print(larger(20))

Which of the following methods will change the string Python Programming into PYTHON PROGRAMMING ?

upper()

Which of the following is a good name for a new custom module?

url.py

Which of the following standard libraries is used to access a file stored on a website?

urllib

Which statement converts a sequence of bytes called my_bytes into a 4-byte integer?

val = struct.unpack('>l', my_bytes)

Which code sorts the numbers in descending order? def partition(numbers, i, k):midpoint = i + (k - i) // 2pivot = numbers[midpoint]done = Falselow = ihigh = k##Missing codeelse:temp = numbers[low]numbers[low] = numbers[high]numbers[high] = templow = low + 1high= high - 1return high

while not done: while numbers[low] > pivot: low = low + 1 while pivot > numbers[high]: high= high - 1 if low >= high: done = True

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 = ';')

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:

The file my_list.txt contains 150+250. Which of the following codes 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))

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:

Given the following function, which statements are valid? def square_root(x): return math.sqrt(x) def print_val(x): print(x)

y = square_root(49.0) y = 1.0 + square_root(144.0) y = square_root(square_root(16.0)) square_root(9.0) y = print_val(9.0) print_val(9.0)

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? items = {1: {'name': 'Chair', 'type': 'Plastic', 'size': 'Small'}, 2: {'name': 'Sofa', 'type': 'wooden', 'size': 'Large'}}items[3] = {}items[3]['name'] = 'Table'items[3]['type'] = 'Wooden'items[3]['size'] = 'Middle'print(items[3])

{'name': 'Table', 'type': 'Wooden', 'size': 'Middle'}

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

If factor = 24 , which format will generate **24, right aligned in its field?

{factor:*>4}

What will be the date type for type(list_name.sort()) and type(sorted(list_name)) ?

< class 'NoneType'>, < class 'list'>

What is the value stored in new_list ? my_list = [[10, 10], [100, 100], [500, 500, 1000]]for val in my_list:new_list = [i for i in val if i>10]

[500, 500, 1000]

What is output? new_list = [['hello', 'word'], 'good morning', 'have a nice day']print(new_list[0:2])

[['hello', 'word'], 'good morning']

Call a function named print_age, passing the value 21 as an argument.

print_age(21)

Which correctly passes two integer arguments for the function call calc_val(...)?

(99, 44 + 5)

Given a function definition: def calc_val(a, b, c): and given variables i, j, and k, which answer shows valid arguments in the call calc_val(...)

(k, i + j, 99)

Which correctly defines two parameters x and y for a function definition: def calc_val(...):?

(x, y)

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 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('{} {} = {} {}'.format(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 Meter1 Kilojoule = 1000 Joule or 1 Kilojoule is equal to 1000 Joule1 Litre = 1000 Millilitre or 1 Litre is equal to 1000 Millilitre

What will be output for '{x:.5f}'.format(x=1.6180339) ?

1.61803'

What is output? new_string = 'One giant leap for mankind'print(new_string[0:6])

One gi

What is output? new_string = 'Python'print(new_string[0:-1:2])

Pto

What is output? new_string = 'Python'my_index = 0while my_index != len(new_string)/2:print(new_string[my_index:int(len(new_string)/2)])my_index += 1

Pyt yt t

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)

A _____ defines the minimum number of characters that must be inserted into the string.

field width

Consider the lists my_list = [['The', 'Magic'] , ['Rhonda', 'Byrne']] and new_list = [] . Select the option that will produce The Magic : Rhonda Byrne as the output.

for i, j in enumerate(my_list): for item in my_list[i]: new_list.append(item) print('{} {}: {} {}'.format(new_list[0], new_list[1], new_list[2], new_list[3]))

Choose the option that gives great as the output.

my_list = ['books', 'are', 'great', 'for', 'learning'] my_list.sort() print(my_list.pop(3))

Choose the option in which the value of new_list is ['greetings'].

my_list = ['hello', 'greetings', 'hi', 'hey'] new_list = [i for i in my_list if len(i)>5]

Which of the following codes 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]### fill the code here ###print(my_list)

my_list.extend([1, 4]) my_list.sort()

Given a list my_list = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] , how would you access the value 7?

my_list[2][1]

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)

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

Define function print_teenager with parameter age. If age is less than 13, print "Too young". If greater than 19, print "Too old". Otherwise, print "Has been a teenager for" followed by the result of computing age - 13 followed by "years.". End with a newline. Sample output with input: 14Has been a teenager for 1 years.

One possible answer is def print_teenager(age): if age < 13: print("Too young") elif age > 19: print("Too old") else: print("Has been a teenager for", age - 13, "years.")

What is output? my_dict = {x: x*x for x in range(0, 6)}second_dict = {} #new dictionaryfor keys, values in my_dict.items():if values <= 16:second_dict[keys] = values#Adding second_dict as an element of my_dictmy_dict["second_dict"] = second_dict for key, value in my_dict['second_dict'].items():print("{}:{}".format(my_dict['second_dict'][key], key), end=' ')

0:0 1:1 4:2 9:3 16:4

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

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 the output of the following code? new_list = [10, 20, 30, 40]for i in new_list[:]:print(i)new_value = new_list.pop(0)

10 20 30 40

What is the length of the dictionary my_dict = {'Country':'India', 'State': {'City':'Delhi', 'Temperature':40}} ?

2

Reference the following program to answer the next four questions: def print_pi(): print(3.14159) print_pi() print_pi()

2 functions call to print_pi() 1 function definition of print_pi() 2 output statements would execute in total 1 print statement exists in the program code

Chapter 1 Statements that are true.

Polymorphism refers to how an operation depends on the involved object types. Static-typed languages require that the type of every variable is defined in the source code. A dynamic-typed language like Python checks that an operation is valid when that operation is executed by the interpreter. If the operation is invalid, a run-time error occurs. If my_func1() and my_func2() are defined functions, then the expression my_func1(my_func2) passes the my_func2 function object as an argument to my_func1. Functions are compiled into bytecode when the function definition is evaluated by the interpreter. A benefit of functions is to reduce redundant code. Incremental development may involve more frequent testing, but ultimately leads to faster development of a program. Forgetting to return a value from a function is a common error. Returning the incorrect variable from a function is a common error. Copying-and-pasting code can lead to common errors if all necessary changes are not made to the pasted code. A local variable is defined inside a function, while a global variable is defined outside any function. A function definition must be evaluated by the interpreter before the function can be called. A programmer can protect mutable arguments from unwanted changes by passing a copy of the object to a function. Adding an element to a dictionary argument in a function might affect variables outside the function that reference the same dictionary object. The statement return a, b, [c, d] is valid.

What is a docstring?

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.

What is output? def division(a, b):try:div = a / bprint('Quotient: {}'.format(div))except:print('Cannot divide {} by {}'.format(a, b))division(10, 2)division(2, 0)division('13',2)

Quotient: 5.0Cannot divide 2 by 0Cannot divide 13 by 2

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

Identify all the keys (including nested dictionaries) in students = {"Semester_1" : {"Aston":20, "Julia":25}, "Semester_2" : {"Ben":21, "Lisa":26}} .

Semester_1, Semester_2, Aston, Julia, Ben, and Lisa

For the next two questions, assume the function below is defined: def split_check(amount, num_people, tax_percentage, tip_percentage): # ...

What value is passed as the tax_percentage argument in the following function call? split_check(60.52, 5, 0.07, tip_percentage=0.18) : 0.07 What value is passed as the num_people argument in the following function call? split_check(tax_percentage=0.07, 60.52, 2, tip_percentage=0.18) ERROR

What is output? my_string = 'What is your name?'print(my_string.split('?'))

['What is your name', '']

What is the output? new_list = [['abc', 'def'], 10, 20]print(new_list[0])

['abc', 'def']

What is the value of new_list ? my_list = [['hey', 'hello', 'hi'], 'good morning']new_list = [i + '!' for i in my_list[0]]

['hey!', 'hello!', 'hi!']

What is the value of sys.argv, len(sys.argv) for the command-line input > python prog.py 1 January 2020 ?

['prog.py', '1', 'January', '2020'], 4

What is the output? new_list = ['python', 'development']new_list.append('in progress')print(new_list)

['python', 'development', 'in progress']

What is the 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 the value of new_list ? my_list = [1, 2, 3, 4]new_list = [i**2 for i in my_list]

[1, 4, 9, 16]

What is the output? new_list = [10, 'ABC', '123', 25]my_list = new_list[:]new_list[2] = 16print(new_list)print(my_list)

[10, 'ABC', 16, 25] [10, 'ABC', '123', 25]

What is output? my_list = [20, 25, 'hello']new_list = my_list[:]print(new_list[0:2])print(my_list[-1])

[20, 25] hello

What is the output of the following code? new_list =[10, 20, 30, 40]for i in range(len(new_list)):if new_list[i] != new_list[-1]:new_list[i] *= 2print(new_list)

[20, 40, 60, 40]

What is the 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] += iprint(new_list)

[32, 245, 723, 1145, 645]

What is the 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 is the output? b1 = [7, 5, 9, 6]b1 = sorted(b1)b2 = b1b2.append(2)print(b1, b2)

[5, 6, 7, 9, 2] [5, 6, 7, 9, 2]

What is the 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]]

What is the value of kv_List ? kv_List = [{'k': {'v': 2}}, {'k': {'v': 15}}, {'k': {'v': 8}}]kv_List.sort(key=lambda e: e['k']['v'], reverse=True)

[{'k': {'v': 15}}, {'k': {'v': 8}}, {'k': {'v': 2}}]

Complete the following code to print the average of the list. new_list = [0, 1, 2, 3, 4]XXXprint('The average is {}'.format(avg))

avg = sum(new_list)/len(new_list)

What is the output? my_list = [['a b c'], ['d e f']]new_list = my_list[0][0].split(' ')print(new_list[-2])

b

What XXX will left align the values in the columns? XXXprint(format_print.format(name='Product', price='Price(cash)'))print('-' * 24)print(format_print.format(name='Banana', price=1.02))print(format_print.format(name='Apple', price=5.08))

format_print = '{name:<16}{price:<8}'

What is the output? my_list = ['hello', 'good', 'morning']print(my_list[1][:3])

goo

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


Ensembles d'études connexes

Chapter 18: Shareholders' Equity

View Set

Unit 3 Lesson 6 Piecewise functions

View Set

Nursing Management: Patients With Hearing and Balance Disorders

View Set

CS-4451 Computer Security Ch1-15

View Set