the cs test

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

import datetime as dt my_dates = ["2017-12-28T05:38:09" "2017-10-14T01:08:32", "2017-03-04T21:18:22"] dates_ordered=[] for i in my_dates: dates_ordered.append(dt.datetime.strptime( i, ___________)

"%Y-%m-%dT %H:%M:%S")

content = 'Learning Python is intresting especially when using strings' x = content.find('in',6) result = content[x:30].capitalize() print(result.center(20,'#') What will be displayed on the screen

####Interesting####

In the code shown in the answer area, an operator will allow the expression to be evaluated correctly from left to right. Which operator should you use?

%

You are working on the code shown in the answer area. You need to evaluate each operator and select the one the results with the smallest value Which operator should you use?

%

MyStr = "Python is the best programming Language!" myStr = "Python is fun to learn!" text = myStr * 2 what is the value of text?

'Python is fun to learn!Python is fun to learn!'

You need to create a leaderboard output in the following format: Dave *** 100,000 Steve *** 90,000 Amy *** 79,500 In the leaderboard output, the usernames are 8 spaces and the '***' starts at position 9. The score has a space preceding it and is displayed with commas. How should you complete the code?

'{0:8} *** {1:,}':format(person,score)

You have the following variables: a = 3 b = 2 Which operator should you place between a and b to get the value 9?

**

You need to select an operator so that the printed value of z is 5.0 Which operator should you use?

**

print the elements separated by sep def print_them(*elements, sep=","): sep: seperator return sep.join(elements) print(print_them.__doc__) Which documentation will be displayed in the output?

*elements: list of elements sep: seperator

items = [1,3,'13'] values = 0 for i in items: if type(i) == list: for j in i: if j % 2 != 0: break values += j elif type(i) == str: values -= int(i) print(values) Which will be printed on the screen?

-13

1 def findIt(item, items) 2 if item in items: 3 return True 4. else: 5. return False 6. 7 print(findIt(3,[2,4,5,6,7,8,9])) Which lines contains error

1

amount = 1250 You need to write a print statement so that the amount will be printed as follows and aligned to the right in the space provided in the print statement: 1250.00 How should you complete the print statement?

10.2f

1 items = [] 2 item = 0 3 4 def get_data(): 5 for i in range(1,5): 6 item = input("Enter a grade: ") 7. items.PPEND(ITEM) 8 9 def avg(): 10. sum = 0 11 for i in items: 12. sum += i 13. return round(sum/len(items), 2) 14. 15 get_data() 16 print(avg()) You input 78, 85, 95, and 96 Which line contains error

12

def do_something(balance): balance += 2 return balnce * 2 x = 4 y = do_something(x) what is the value of y?

12

Which expression would evaluate to 3?

13//4

James: 1 Bryan:2 Lisa:3 Jessica:4 Russ:2 The file is in the same directory as the file containing the code below, and it is only used by this application. You run the following code: values = 0 with open("info.txt", "a") as my_file: my_file.write("Tom:2") try: info_file = open("info.txt", "r") content = info_file.readlines() for item in content: values += float(item.split(':')[1]) info_file.close() except Exception: print("Could not open the file!") print(values) What will be displayed on the screen?

14.0

For each of the following statements, select Yes if the statement is true. Otherwise, select No.

3 + False evaluates to False: NO True + 1 evaluates to 2: YES True and False evaluates to False: YES True and true evaluates to True: NO Type(False) is <class 'int'>: NO

y = 2 x = 0 while x * y < 8: if x == 3: pass while x < 2: x = x + 1 x += 1 What will be the value of x?

4

You have the following expression: 6 // 4 % 5 + 2 ** 3 - 2. How will it evaluate?

7

w_list = ['dog',bear'] x=0 for word in w_list: for i in range(len(word)): x = x + 1 if x > 6: break What is x

7

Which expression evaluates to 3? NOT A DUPLICATE DIFF ANSWERS

7 % 2 * 3

You have the following code: x = 2 y = 6 x += 2 ** 3 x -= y // 2 // 3 print(x) What will the final statement print after the code is executed?

9

paycheck = 2500 bonus = 0 if paycheck <= 1500: bonus = 750 elif paycheck > 2000 and paycheck < 2500: bonus = 900 elif paycheck > 2000: bonus = 800 if paycheck >= 2500: bonus = 950 What is the value of the bonus

950

You are working on the code shown in the answer area. You need to evaluate the expressions to decide on a suitable operator placed between x and y so 'we made it' is printed on the screen. Which operator should you use? To answer, select the appropriate option from the drop-down menu.

<

You need to evaluate the expressions to decide on a suitable operator placed between x and y so 'we made it' is printed on the screen. Which operator should you use?

<

You need to produce the following output: rat bat barn Which code should you insert?

<= 4:

x = 3 text = 'I have ' + x + ' cars in my garage.' What is the value of text

An error will be generated

f = open('numbers.txt') f.readall() Which exception will be raised?

AttributeError

student_info = [67,89,95,80,83] grade = sum(student_info)//len(student_info) index = -1 system = [1:"A", 2:"B", 3:"C", 4:"D", 5:"F"] if grade >= 90 and grade <= 100: index = 1 elif grade >= 80 and grade < 90: index = 2 elif grade >= 70and grade < 80: index = 3 elif grade >= 60 and grade < 70: index = 4 else: index = 5 print(system[index]) What grade will be printed on the screen?

B

You have the following code: import random my_list = ['Ruby','Python','Java','PHP'] You need to print a random value from my_list. For each of the following statements, select Yes if the statement would print a random value from my_list. Otherwise, select No.

No, Yes, Yes, Yes

def calc1(rate, item): item *= (1 + rate) rate = 0.25 item = 12000 calc1(rate, item) print('Rate:', rate, '; Value:', item) What will be displayed on the screen?

Rate: 0.25 ; Value: 12000

What should the user enter as the day value for the percent_discount to be 10?

Sunday

For each of the following statements, select Yes if the statement is true. Otherwise, select No.

The print statement will display True a = 45 b = 45 print(a is not b): NO The print statement will display True test1 = "This is a test" test2 = 'This is a test.upper() print(test1 is test2): NO The print statement will display True c = [2,4,7] d = [2,4,7] print(c is d): NO The print statement will display True print('h' in Python): YES The print statement will display True print('is' in 'This IS a test'): YES

For each of the following statements, select Yes if the statement is true. Otherwise, select No.

The pydoc module can generate documentation served in a Web browser: YES The pydoc module can generate documentation saved to HTML files: YES The pydoc module can generate documentation saved to PDF files: NO The pydoc module can generate documentation in a console: YES

You run the following code four times: print("Enter a value:") val = input() print("The type of val is: ", type(val)) For each run, you enter a single value as follows: 54654756493 False 68959995.5466 This is only a test Which output will be displayed for the four runs?

The type of val is: <class 'str'> The type of val is: <class 'str'> The type of val is: <class 'str'> The type of val is: <class 'str'>

You have the following code: x = 10 + 1.1 + float(4.1E-2) What is the value of x?

The value of x is 11.141

You have the following code: x = 3 / 3 + 3**3 What is the value of x?

The value of x is 28.0

For each of the following statements, select Yes if the statement is true. Otherwise, select No.

Using a mix of single and double quotes in my_str will cause an error: NO The following code will print 41: NO The type of new_val is int: NO my_bool evaluates to 12: YES The following will print 'Here is what I have: 4.5': YES

You have the following line of code: z = float('32.9') Which expression evaluates to 2?

bool(z) + True

You have the following Python files: c:\temp\myModule\add.py c:\temp\myModule2\add.py c:\tmp\myModule\add.py c:\temp\add.py You have a terminal open and are in the "c:\temp" directory. You run the following command: python -m pydoc myModule Which python file will pydoc attempt to create documentation for?

c:\temp\myModule\add.py

def calc(amount = 5, rate = 2): if amount > 5: return amount * rate else: return amount * 2 * rate Which function call results in 4?

calc(1)

You need to create a custom exception for your application Which code should you use

class MyException(Exception): pass

given lorem.txt try: lorem = open("lorem.txt", "r") __________________ lorem.close() except Exception: print("Could not open lorem.txt!") print(content)

content = lorem.read()

elements = (12,2,8,5,14,6,22,35,18,4) items = {1:"C", 2:"C++", 3:"Java", 4:"Python", 5:"JavaScript", 6:"Go"} count = 0 for e in elements: if e in items: ______________________ count +e print(count)

continue

def calc_area_triangle(l, b, h): return b * H / 2 area = calc_area_triangle(0, 3, 4) print(area) You need to fix the error. Which code should you use to fix the error?

def calc_area_triangle(l, b, h): return b * h / 2

You need to add code to catch multiple exceptions in one exception block. Which line of code should you use?

except(ZeroDivisionError, TypeError) as e:

You have a file named VotingDate.txt. You need to open the file for writing in binary format only. Which code segment should you use?

f = open('VotingData.txt', 'wb')

You need to write some contents to a file named file_name that will be in the following format: Hello World! Which code segment would you use?

f = open('file_name', 'w') f.write('Hello World!') f.close()

Which line of code should u use with open('PurchaseOrders.txt', 'w+') as f: f.write('some data\n') ____________ data = f.read()

f.seek(0)

You need to complete the code so that c has a value of 4. Which line of code should you use?

for j in my_list[i]:

You need to add code so that the value of total is 10. Which code should you use?

set(list_a) - set(list_b)

words = "The cow has spots and walks slowly." my_sentence = words[-7] my_sentence = words[-7:] + words[:8] my_sentence = my_sentence + words[4:7] What is the value of the variable my_sentence

slowly.The cow cow

You have the following variables: a = '6' b = '5' What is the data type of a + b?

str

You have the following declarations: my_stringA = 'I like Pie.' my_stringB = 'Kids like toys.' my_stringC = 'It is hot in the sun.' You need to write code that will print the following message on the screen: Python Which code segment should you use?

text = my_stringA[7] + my_stringB[=3] + my_stringB[-5] + my_stringc[6] + my_stringB[11] + my_stringC[-2] print(text)

You execute the following code: my_list = 'C Java' languages = list(my_list) languages.append('Python') print(languages) What will be the value of languages?

['C', ' ', 'J', 'a', 'v', 'a', 'Python']

def build_names(): names = ["Ariel","Matt","John","Susie","David","Steve","Douglas"] return names[1:5] def change_names(elements): new_elements = [] for e in elements: new-elements.append(e[0:2].upper()) #new-elements.sort() return new-elements print(change_names(build_names())) What will be displayed

['Ma', 'JO', 'SU', 'DA']

if account_type.lower()=='d': if invoice_amount>= 100: print('needs management approval') else: print('amount approved') elif account_type.lower() == 'a': if invoice_amount >= 100 and invoice_amount <= 1000: print('add to weekly report') else: print('please stop by HR') U have to add code to the beginning so that the amount will need director approval. What code should be used

account_type = 'A' invoice_amount = 100

You have the following code: def add(a=0, b=0): return a + b Which of the following is NOT a valid way to call the add function?

add a=3, b=5

Java Python Ruby You have the following code: programming = {"Java":1, "Python": 2, "Ruby": 3} programming2 = {1:"Java", 2:"Python", 3:"Ruby"} for i in range(1,5): print(programming2[i]) You need to resolve the following error with the code: Traceback (most recent call last): File "c:/PythonLearning/programming.py", line 5, in <module> print(programming2[i]) KeyError: 4 Which lines of code should you use to replace the existing for loop?

for i in programming2: print(programming2[i])

You are developing a shopping website You need to offer customers the Bronze level if they accumulate between 500 and 600 points in shopping. Which code block should you use?

if 500 <= points <= 600: level = 'Bronze'

You need to complete the code so x has a value of 6 Which line of code should you use?

if i in numbers:

You need to write the following into a CSV file: students = [["Mark", "A"], ["Bryan", "B"], ["Lisa", "B"],["Jessica", "C"], ["Tim", "A"]] Which code segment should you use?

import csv with open("students.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(students)

24, Dec 2017 was a great day! 24, Dec 2017 represents the current month and year. what code segment should you use?

import datetime today = datetime.date.today() print("{:%d, %b %Y} was a great day!".format(today))

In the code shown in the answer area, an operator is needed so that the value of result is True Which operator should you use?

is

You are working with the code shown in the answer area. You need to select the loan amount so that the rate will be 0.2. Which loan amount should you use? To answer, select the appropriate option from the drop-down menu.

loan_amount = 551

import math my_list = [.3,.3,.3,.1,.1] You need to calculate the total of the items in the list. Which code should you use?

math.fsum(my_list)

You need to code a function to implement the formula to calculate the area of a circle (pi times r squared). Which code should you use?

math.pi * math.pow(r,2)

Select yes if my_dates will raise an exception my_dates = ["12/24/2017 13:22", "10/11/17 01:49:59", "12/5/17", "11/29/2017"] d1 = dt.datetime.strptime(my_dates[0]. "%m/%d/%Y $H:%M") d2 =dt.datetime.strptime(my_dates[1]. "%m/%d/%Y $H:%M:%S") d3 =dt.datetime.strptime(my_dates[2]. "%m/%d/%y) d4 =dt.datetime.strptime(my_dates[3]. "%m/%d/%Y)

my_dates[0] - YES my_dates[1] - NO my_dates[2] - NO my_dates[3] - NO

You have the following declaration: my_items = ([8, '7', 1+2j, False]) Which line of code assigns <class 'list'> to my_type?

my_type = type(my_items)

print("Determining the data types") # --Add missing code here-- print(type(my_var)) print("Wrapping up the program!") you need to add a line so that <class 'int'> will be in the output window which line should you add?

my_var = 2**2

count = input('Enter the number of students in the class: ') #add the missing line here print(new_count) You need to add a line of code so that when the user enters 15, new_count will be 20 Which line of code should you use?

new_count = int(count) + 5

U need to print a list of files in the c:\tmp directory

os.chdir(r'c:\tmp') print(os.listdir())

You need to create the following directory tree on a Windows computer: c:\Python\practice\myFolder Which code should be used

os.makedirs(r'c:\Python\practice\myFolder') BE CAREFUL THIS ONE IS A ONE LETTER DIFFERENCE PICK THE ONE WITH S IN IT

You need to generate a password using three items from a list of words named my_word. Which code should you use?

print("".join(random.SystemRandom().choice(my_words) for i in range(3)))

amount = float(input("Enter the mortgage amount: ")) the user enters 325154.5687 which statement will print 325,154.57 on the screen?

print("{:,.2f}".format(amount))

You need to complete the code so True is output to the console Which line of code should you use?

print(extra_colors is more_colors)

def print_dir(*elements, sep=""): return "C:\\%s" % (sep.join(elements)) Which will cause error

print(print_dir('Program files', None))

import sys You need to add code to print the location on the computer where the Python interpreter is installed. Which line of code should you use?

print(sys.executable)

You saved the following code in a file named Example2.py: Calculates the distance from rate and time Finds the distance between two points __author__ = "Python tester" __copyright__ = "Copyright 2019, The Learning Project" import math def calc_distance(rate, time) return rate * time def points_distance(x1,x2,y1,y2): The difference of the x squared and the difference of the y squared return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) You execute the following command: python -m pydoc Example2 What will be displayed in the FUNCTIONS section when the command is executed?

problem in Example2 - IndentationError: expected an indented block (Example2.py, line 17)

You need to start a web server to access the documentation of the files you are working on in the current directory, in addition to the Python documentation. Which command should you use?

python -m pydoc -p 9898

You need to add code to create a list of 10 random integers between 1 and 10 inclusive. Which code should you use?

randInts = [random.randint(1,10) for i range(1,11)]

You are writing a Python program that calculates a student's average grade. When The program is run from the command line, the user will provide the student name followed by multiple grades. You need to complete the code so that the program prints the student's name and the average grade. Which code segments should you use?

range(2, len(sys.argv)) format(sys.argv[1], sum/(len(sys.argv)-2))

a, b, c, and d are defined as follows: a = 7 b = 3 c = 5 d = 1 Which line of code assigns 9 to result?

result = a + d * 2

a=7 b=3 c=5 d=1 Which line of code assigns 9 to the result?

result = a+d *2

The variable named test is declared as follows: test = "TEST" Which line of code assigns 'TT' to result?

result = test[0] + test[-1]

Which string declaration spans more than one line and respects whitespace when the string is printed on the screen?

str4 = """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."""

You need to add code to save the output of the print statements to the output.txt file. Which code should you insert?

sys.stdout = fh

def test_scores(total_questions=0, total_correct=0): return int(total_correct) / int(total_questions) Select yes if the statement would cause a runtime error, Otherwise select no

test_score = test_scores(20,19) - NO test_score = test_scores("20","19") - NO test_score = test_scores(1) - NO test_score = test_scores(0, 20) - YES

my_stringA = 'I like Pie.' my_stringB = 'Kids like toys.' my_stringC = 'It is hot in the sun.' What will print python

text = my_stringA[7] + my_stringB[-3] + my_stringB[-5] + my_stringC[6] + my_stringB[11] + my_stringC[-2] print(text)

You have the following code shown that calculates the total of all items in the list: prices = [1.00, "3.50", 5.05] total = 0 for item in prices: total += item print(total) The code produces the following error: Traceback (most recent call last): File "c:/PythonLearning/programming.py", line 5, in <module> total += item TypeError: unsupported operand type(s) for +=: 'float' and 'str' You need to fix the error. Which error should you use?

total += float(item)

def division(a, b): return a / b division(2, 0) You need to add code to handle a division by zero exception. Which code should you use?

try: division(2,0) except ZeroDivisionError as e: raise ValueError("Cannot divide by zero.") from e

You need to complete the code so the number 1 is output to the console. Which line of code should you use?

v + x // y % z

myStr = 'To Python or not to Python, that is the question!' #Add missing line here You need to add a line of code so that 46 will be assigned to val Which line of code should you use?

val = myStr.rfind('on')

You have the following declarations: s = 'Strings in Python!' s2 = 'Interesting' Which code assigns 'in' to var?

var = s[3] + s[4]

s = 'Strings in Python!" s2 = 'Interesting' Which code assigns 'in' to var

var = s[3] + s[4]

n = 4 x = 1 You need to print out a multiplication table for 4 x 1 through 4 x 10, with each output on a separate line. The first output should be: 4 x 1 = 4 The last output should be: 4 x 10 = 40 Which code segment should you use?

while x < 11: print(str(n) + ' x ' + str(x) + ' = ' + str(n*x)) x += 1

x=1 y = 0 z = 2 t = 35 result_1 = result_2 = result_3 = result_4 = 0 What prints out 10

while y <=10: if y % 3 == 0: result_2 -=1 else: result_2 +=3 y+= 2 print(result_2)

import pickle course_count = [["C++", "24"], ["Java", "32"], ["Python", "38"], ["JavaScript", "29"], ["C#", "40"]] #add missing code here with open("languages.bin", "rb") as f: course_count2 = pickle.load(f) print(course_count2) You need to add the missing code to write the list to a binary file. Which code fragment should you use?

with open("languages.bin", "wb") as f: pickle.dump(course_count, f)

x = 3 x += 1 #add code here U need to add a line of code so that x = 16 What code is right

x **= 2

You have the following code: v = bool([False]) x = bool(3) y = bool("") z = bool(' ') Which of the variables will equal false?

y will equal false


Ensembles d'études connexes

chapter 8 section 8.1 measurement of pulmonary function

View Set

Chapter 9: Food & Supplement Labeling

View Set

Colligative Properties and Osmotic Pressure

View Set

Лексичний мінімум з англійської ЗНО

View Set

microeconomics chapter 9 study quiz

View Set

CompTIA Linux+ Chapter 7 Quiz - 'Shell Scripts'

View Set

USGBC LEED Green Associate Exam Prep

View Set

Constitutional Law II Midterm 1- Texas v. Johnson

View Set