Computer Science

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

bits

0s and 1s are known as ___ .

%

15 _____ 3 = 0

/

15 _____ 3 = 5.0

key

A _____ can be located in a dictionary and is associated with a value.

disk

A _____ is a computer component that stores files and other data.

variable

A _____ is a named item used to hold a value.

keyword

A _____ is a word that is part of the Python language and can't be used as a variable name.

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.

if age >= 9 or height >= 59:

A child is required to use a booster seat in a car until the child is 9 years old, unless the child reaches the height of 59 inches before age 9. Which expression can be used to decide if a child requires a car seat or not?

if days_since_login > 10 and days_since_login < 20:

A company wants to send a reminder email to users who have not logged in for more than 10 days, but less than 20 days. Which expression can be used to decide if a user should get an email or not?

2

A computer processor stores numbers using a base of _____.

case sensitive

A language is called _____ when upper case letters in identifiers are considered different from lower case letters.

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.

instructions

A processor is a circuit that executes a list of _____.

An Algorithm

A sequence of instructions that solves a problem is called _____.

a python code only runs the excep block when

A try and except block is used for error handling in Python. Try : Helps to test the code. If the code inside the try block is error free it is executed

interpreter

A(n) _____ is a program that executes a script.

unary

According to Python's precedence rules, which of the following operators has the highest precedence?

argument

An item passed to a function is a(n) _____ .

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!

2,3,4

Excess indentation must be removed from which lines to make the code correct? 1. print('start') 2. if x > 10: 3. print('large') 4. else: 5. print('small') 6. print('done')

False OR (True AND False) --> False OR False --> False

Given x = 1, y = 2, and z = 3, how is the expression evaluated? In the choices, items in parentheses are evaluated first. (x == 5) or (y == 2) and (z == 5)

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

immutable

Objects like integers and strings that can't be modified are called _____ .

import statement?

Only the length and breadth attributes of ABC.

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

PYTHONPATH

What is an IDE used for?

Program development, including writing the source code.

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.0

Random Access Memory

RAM is an abbreviation that stands for:

whitespace

Space, tab, and newline are all called _____ characters.

1980

The Python language began development in the late _____'s.

open-source

The Python language is developed by a public community of users, therefore Python is a(n) _____ language.

operating system

The _____ is a process that manages programs and interfaces with peripherals.

['one', 'two', 'three', '1', '2', '3']

What are the contents of names_list after the following code is executed? names_list = ['one', 'two', 'three'] digits_list = ['1', '2', '3'] names_list = names_list + digits_list

my_name == your_name

What condition should replace ZZZ to output "Same name" only if the values of two variables are the same? my_name = input("Enter my name: ") your_name = input("Enter your name: ") if ZZZ: print("Same name")

color is 'red' and style is 4

What conditions have to be true to make the following code display "B"? if color == 'red': if style < 3: print('A') elif style < 5: print('B') else: print('C') elif color == 'blue': print('D')

one\two\\three

What does print("one\\two\\\\three") display?

code

What is a common word for the textual representation of a program?

0

What is displayed when the following code is executed?

23rd

What is displayed when the following code is executed? day = 23 if day % 10 == 1: ending = "st" elif day % 10 == 2: ending = "nd" elif day % 10 == 3: ending = "rd"else: ending = "th"print(str(day) + ending)

AB

What is output when the following code is executed? score = 65 group = ''if score <= 60: group = group + 'A' if score <= 70: group = group + 'B' if score <= 80: group = group + 'C' else: group = group + 'D' print(group)

9

What is the base 10 representation of the binary number: 00001001?

46

What is the base 10 representation of the binary number: 00101110?

00001100

What is the base 2 representation of the decimal number: 12?

00100011

What is the base 2 representation of the decimal number: 35?

0

What is the ending value of a when b is assigned with the value 5? a = 7 a = b + 5 if b > 5 else 0

1.0

What is the ending value of z? x = 0.3 z = math.pow(math.ceil(x), 2)

21

What is the final value of z? grades = { 'A': 90, 'B': 80, 'C': 70, 'D': 60 } my_grade = 70 if my_grade not in grades: z = 1else: z = 2 if 'F' in grades: z = z + 10 else: z = z + 20

float

What is the name of the data type used for floating point numbers

Prints 'loop' forever (infinite loop)

What is the output? count = 0 while count < 3: print('loop') count = count + 1 print('final value of count:', count)

17

What is the output? my_list = [2, 8, 3, 1, 18, 5] print(my_list[3] + my_list[1] * 2)

An error: the string does not represent an integer value

What is the result of the expression: int('1750.0')?

5

What is the value of 11 // 2?

13

What is the value of test_val after the following code is executed? a = 12 test_val = 6 if a * 2 == test_val: a = a + 7 else: test_val = 2 * a test_val = a + 1

_main_

What is the value of the __name__ built-in variable in a module that is executed as a script by the programmer?

-2

What is the value of x after the following code is executed? x = 15 x = x + 1 x = x * 2 x = 30 - x

1

What is the value of x after the following code is executed? x = 17 if x * 2 <= 34: x = 0 else: x = x + 1 x = x + 1

9

What is the value of x after the following code is executed? x = 7 If x < 7 x = x + 1 x = x + 2

12

What is the value of y after the following code is executed? Note that the question asks for y, not x.

2.5

What is the value of: 1 + int(3.5) / 2?

15

What is x's final value? x = 10 y = 20 if y <= 2 * x: x = x + 5 else: x = x * 2

{1, 2, 3, 4, 5, 6}

What values are in result_set after the following code is run? my_set = {1, 2, 3, 4, 5, 6} other_set = {2, 4, 6} result_set = my_set.union(other_set)

{ }

What values are in result_set after the following code is run? my_set = {1, 2, 3, 4, 5, 6} other_set = {2, 4, 6} result_set = other_set.difference(my_set)

if-else

Which branch structure does a program use to output "Yes" if a variable's value is positive, or "No" otherwise?

(x * y) / 2

Which code example is an expression?

list

Which data type is the correct choice to store a student's test scores in chronological order?

set

Which data type is the correct choice to store the names of all the hockey players who have scored 3 or more goals in a single game in no specific order?

dict

Which data type is the correct choice to store the number of wins associated with each basketball team in the NBA?

if user_unit in accepted_units:

Which determines if user_unit is in the list accepted_units? accepted_units = [ 'in', 'cm', 'mm', 'km', 'miles' ]

(float(first_num) + float(second_num)) / 2

Which expression calculates the average of first_num and second_num? first_num = input('Enter the first number: ') second_num = input('Enter the second number: ')

not (10 < x < 20)

Which expression can be used to decide if x is not between 10 and 20?

seconds // 60

Which expression gives the number of whole minutes that corresponds to some number of seconds?

x = x + 5 if age < 18 else x + 1

Which expression is equivalent to the following code? if age < 18: x = x + 5 else: x = x + 1

((not x) and (y == a)) and b

Which expression is equivalent to: not x and y == a and b?

x - ((y * (-z)) / 3)

Which expression using parentheses is equivalent to the following expression: x - y * -z / 3

YYY: user_age < 20 ZZZ: user_age > 10

Which expressions for YYY and ZZZ will output "Young" when user_age is less than 20 and "Young but not too young" when user_age is between 10 and 20?

2.3e7

Which floating-point literal correctly represents the scientific notation value: 2.3 x 10^7?

d

Which formatting presentation type is used to display an integer?

X

Which formatting presentation type is used to display the integer 43 as 0X2b (hexadecimal in uppercase)?

int()

Which function converts a string to an integer?

if x = y:

Which has an error? Assume x = 10 and y = 20.

print()

Which instruction displays variables or expression values?

The first print() statement must be indented.

Which is true of the badly formatted code? x = input() if x == 'a': print('first') print('second')

print(len(sales["apples"]))

Which line in the following program causes a runtime error? sales = { "apples": 0, "lemonade": 0 } sales["apples"] = sales["apples"] + 1 del sales["lemonade"]print(len(sales["apples"]))

my_list = [7, 2, -8, 16]

Which of the following assignment statements creates a list with 4 integer elements?

The speed of a snail.

Which of the following data values is best represented with a floating point variable?

7.5 + (x / 2)

Which of the following expressions causes an implicit conversion between types? Assume variable x is an integer, t is a float, and name is a string.

max_age

Which of the following identifiers is valid?

2x + 3y

Which of the following is NOT a valid expression? Assume x and y are integer variables.

The element at index 1 is 'JFK'

Which of the following statements about my_list is false?

my_set = set([1, 2, 3])

Which of the following statements assigns a new variable, my_set, with a set that contains three elements?

age + 2 = years

Which of the following statements has a syntax error? Assume age and years are variables that have already been defined.

string_1[1] = 'B'

Which of the following statements produces an error? Assume string_1 = 'abc' and string_2 = '123'.

companies.remove('Google')

Which of the following statements removes the value 'Google' from the set, companies? companies = { 'Apple', 'Microsoft', 'Google', 'Amazon' }

_ (underscore)

Which of the following symbols can be used as part of an identifier?

*

Which operator is evaluated first: x + y < y - z * 2 ?

+

Which operator is evaluated last in an expression?

dict

Which pair shows the correct classification of the given data type?

print(sys.argv)

Which print statement displays the value of a variable called argv in a module called sys?

print('{:s} had {:f} million people in {:d}'.format('Tokyo', 9.273, 2015))

Which print statement displays: 'Tokyo had 9.273000 million people in 2015'?

print(r'C:\\Users\\Mika\\grades.txt')

Which print statement would display 'C:\Users\Mika\grades.txt' (without the single quotes)?

print(chr(65))

Which print statement would display the letter 'A'? (Note that the code point for the letter 'A' is 65.)

print('I won\'t quit!')

Which print statement would display: I won't quit!

IDLE editor

Which program can be used to create a Python file that can be used directly by the interpreter?

ValueError

Which runtime error type occurs when trying to convert 'abc' to an integer?

airport_code = 'JFK'

Which statement assigns the string variable airport_code with the value JFK?

fruits_dict["Lemon"] = 0.75

Which statement changes the value associated with key "Lemon" to 0.75 in the dictionary fruits_dict?

List items can be changed, while tuple items can't be changed.

Which statement correctly explains a difference between lists and tuples?

print('First part...', end='')

Which statement does not print a newline character at the end?

x + y = z

Which statement has a syntax error? Assume variables x, y, z, and age have already been defined.

x = x - (2 + y)

Which statement is equivalent to the following assignment? x -= 2 + y

t = 'minute' if x == 1 else 'minutes'

Which statement is equivalent to the following? if x == 1: t = 'minute' else: t = 'minutes'

pop() removes a random item in the set.

Which statement is true regarding the pop() method for sets?

import math

Which statement makes the code in the math module available?

print("I won't quit!")

Which statement outputs the text: "I won't quit!"?

user_name = input()

Which statement reads a user-entered string into variable user_name?

del cars_dict["1G1JB6EH1E4159506"]

Which statement removes entry "1G1JB6EH1E4159506" from the dictionary cars_dict?

my_list.pop(len(my_list)-1)

Which statement removes the last element of my_list?

#

Which symbol is used in Python to create a comment?

*

Which symbol represents the multiplication operation in programming?

logic error

Which type of error does not cause the program to crash?

compiler

Which type of program converts a high-level language program into machine instructions?

B

With the logic block shown below, what is output when grade is assigned with the value 75? If grade < 50 Put "F" to output Else If grade < 60 Put "D" to output Else If grade < 75 Put "C" to output Else If grade < 85 Put "B" to output Else If grade <= 100 Put "A" to output Else Put "Invalid grade" to output

import csvwith open('data.csv','r+') as file:csvFile = csv.reader(file)for row in csvFile:print(row)

['Product Name', ' Price']

is run on the terminal?

['my_script.py', 'input.txt', 'output.txt']

Garbage collection

_____ is the process where objects that are no longer needed are deleted.

from math import (pi, exp, log)import urllibprint(__name__)

__main__

A python code only runs the except block when _____.

an error occurs in the preceding try block

from Shapes.Square.dimensions import area

area

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

as

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

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

The with statement creates a(n) _____ which performs setup and teardown operations.

context manager

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

except (NameError, AttributeError):

new_string = 'Python'my_index = 0try:while my_index != len(new_string) / 2:print(new_string[my_index:len(new_string)/2])my_index += lXXXprint('Error Occurred')

except (TypeError, IndentationError):

25

except ZeroDivisionError as e:print(e)

Python uses _________ constructs to handle errors during execution.

exception-handling

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

my_list = [10, 20, 30, 50]XXX

file = open('my_data.txt', 'a+')for i in my_list:file.write(str(i) + '\n')

Which of the following methods forces the output buffer to write to disk?

flush() and close()

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)

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 piprint('The value of pi is: {0:.2f}'.format(pi))

len(my_list)

hich method call returns the number of elements in my_list?

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

.

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

print('The sum of values is: {}'.format(calculate.sum(10, 20)))

import calculate

from circle import (area, radius)if __name__ == '__main__':a = area(6)print('Area: {0:.2f}'.format(a))

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

Identify the code that generates 'os' as output.

import osprint(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 timetime.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.

A custom exception type is usually defined by:

inheriting from the exception class.

def Division(a, b):return (a / b)def Sum(a, b):return (a + b)def main():a = 200.0b = 0.0try:Sum(a, b)Division(a, b)except:print('Error Occurred')main()

main()

from x import powimport ytoday_date = y.date.today()base = 6exponent = 2print('Calculation done on:', today_date)print(pow(base, exponent))

math, datetime

f = open('Numbers.txt')lines = f.readlines()f.close()XXXprint(sum)

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

is true, then ______.

the file is being executed as a script

It is recommended to use a 'with' statement when opening files so that ____.

the file is closed when no longer needed

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

time

def Remainder(a, b):if b == 0:return(b % a)else:return(a % b)XXXfinally:print('Remainder:', z)

try:a = 20b = 0z = 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!')

except:print('Error Occurred')

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

A(n) _____ should be used to specify all the exception types when being handled by a single exception handler.

tuple

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 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 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 = 0for i in line.split('+'):sum = sum + int(i)file.write(str(sum))

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 of the following statements causes a ValueError to occur?

raise Value error

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

reload(print_names)

A programmer will typically write a(n) _____ and pass it to the interpreter.

script

overflow

Assigning a value to a floating point variable that is too large for the computer to represent is a condition called _____ .

math.sqrt(math.pow(a, 2)) + math.pow(b, 2)))

Assume a and b are variables that hold the base and height of a right triangle. The length of the long side (hypotenuse) is calculated as the square root of a^2 + b^2. Which expression calculates the length of the hypotenuse?

output

Basic instruction types are input, process, and _____.

backwards compatible

Because Python 2.7 programs cannot be run by the Python 3.0 interpreter, Python 3.0 is not _____.

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

Which statement about Python is true?

Developers are not usually required to pay a fee to write a Python program.

associative

Dictionaries are containers used to describe a(n) _____ relationship.

runtime

Dividing by zero is an example of which type of error?

's'

If text_line = 'one fish two fish', what is the value of text_line[6]?

true for importing a module:

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

y >= x

If x = 10 and y = 20, which expression is True?

3.0004e-12

In Python, which of the following literals is shown in valid scientific notation?

variables

In an instruction like: z = x + y, the symbols x, y, and z are examples of _____.

prompt

In the statement: age = input('Enter your age: ') , the string 'Enter your age: ' is called a(n) _____.

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!

print('Cannot calculate speed.')

Invalid Time!

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!

Which of the following is true for an environment variable?

It can be accessed by every program running on the computer

mixins

Mixins are classes that provide some additional behavior, by "mixin in" new methods, but are not themselves meant to be instantiated.

escape sequence

The special two-item character sequence that represents special characters like \n is known as a(n) _____.

print(emails_dict["C2104"])

The variable emails_dict is assigned with a dictionary that associates student ids with email addresses. Which statement prints the email address associated with the student id "C2104"?

the use of a catch-all except clause?

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

id()

The built-in Python function that gives an object's identity is:

Moore's Law

The capacity of ICs doubles roughly every 18 months

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.

interest = (principal * interest) * time

The formula for calculating the amount of interest charged on a loan is: interest = [principal x rate of interest] x timeWhich Python statement correctly performs the interest calculation?

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

The function is exited with no return.

compound

The operator *= is called a(n) _____ operator.

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

module object

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)

The reload() function returns the _____.

namespace of the module with updated definitions

Which of the following libraries 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()

A(n) _____ is a directory that gives access to all of the modules stored in a directory when imported.

package


Set pelajaran terkait

Advanced Cell Biology Chapter 2 Oxford Insight

View Set

Biology Chapter 17 Key Questions

View Set

ACCT 3130 Final Exam Quiz Questions Review

View Set

Chapter 9 Health Promotion of the Infant and Family

View Set

Cellular & Molecular Basis of Medicine, Exam 4

View Set

UGA Poultry Processing-Cut Up and Deboning and Marination

View Set

module - 2 Atherosclerosis & Hyperlipidemia

View Set

Chapter 25: Fluid, Electrolyte, and Acid-Base Balance (A & P)

View Set