0% found this document useful (0 votes)
10 views6 pages

Dump 3

The document contains a series of programming questions and code snippets related to Python, focusing on file handling, exception management, data types, and control structures. It includes multiple-choice questions asking for correct code segments to handle specific programming tasks. The content is aimed at assessing knowledge of Python syntax and functionality.

Uploaded by

irfankhan304701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Dump 3

The document contains a series of programming questions and code snippets related to Python, focusing on file handling, exception management, data types, and control structures. It includes multiple-choice questions asking for correct code segments to handle specific programming tasks. The content is aimed at assessing knowledge of Python syntax and functionality.

Uploaded by

irfankhan304701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Question Correct Answer

try:f=open(numbers.txt")except Erro:print 'File does not


exist'.else:print(f.read())fineily:f.close()
You have the following code:You need to add code to
handle a file not found exception.Which code should try:passеxсерт Ехception:passfinally:print (f.read())f.close()
you use?Choose the correct answer
open(numbers.txt')print (f.read())f.close()
try:passеxсерт Ехception:f.read()finally:print (f.read())f.close()

try:f=open ("numbers.txt")except FilellotFoundError:print('File does not


exist.)else:print (f.read())finsally:f.close()
python makes the distinction between integers and floating variables.
Evaluate each situation regarding data types and
answer Yes if it's true or No if it's false. When declaring variables in option, a data type must be specified.

When setting a boolean variable, the value must start with a capital letter.
a=10b=5c=2d=Truex=a+b%dy=d+b**cifx<y:print("we made it")
You are working on the code shown in the answer
ares. You need to evaluate the expressions to decide
on a suitable operator placed between x and y so we a=10b=5c=2d=Truex=a+b+dy=d+b**cifx<y:print("we made it")
made it is printed on the screenWhich operator should
you use? To answer, select the appropriate option from
the drop-down menu.Choose the correct options
a=10b=5c=2d=Truex=a+b/dy=d+b**cifx<y:print("we made it")

a=10b=5c=2d=Truex=a+b//dy=d+b**cifx<y:print("we made it")


print(pieces[5])

Analyze this code example:pieces = ["king", "queen", print(pieces[3])


"rook", "knight", "pawn"] pieces.sort()Which commands
will display the rook?
print(pieces[6])

print(pieces[-1])
'

In Python, which character(s) should be placed before /*


text in a line of code to make that line of code a
comment?
#

//
def division(a, b).return
a/btry:division(4.0)division("3","4")except(ZeroDivisonError,TypeError)
as e:print(f'exception caught "%s" {e}')
You have the code shown in the answer area.You need
to add code to catch multiple exceptions in one
try:division(4.0)division("3","4")except(Error,TypeError) as
exception block.Which line of code should you use? To e:print('exception caught "%s" %e)dof division(a, b).istum a/b
answer, select the appropriate option from the drop-
down menu.Choose the correct options
try:division(4.0)division("3","4")except(ZeroDivisor,TypeError) as
e:print('exception caught "%s" %e)def division(a, b).return a/b

try:division(4.0)division("3","4")except(DivisorError,TypeError) as
e:print('exception caught "%s" %e)
A developer is building a code block to log a current datetime.datetime.today()
date and time for app activity. Which two code snippets
will replace the #current date and time comment with
the correct date and time?import datetimelog_time = datetime.datetime.strptime()
#current date and timeprint("entry time: ",log time)

datetime.datetime.now()

datetime.datetime.strftime()
while x <11print(str()+x+at(X)strin+x))x+=1
You have the following code:n=4x=1You need to print
out a multiplication table for 4 x 1 through 4 x 10, with while x < 11:print(str(n) str()+(x)x+=1
each output on a separate lineThe first output should
be4x10=4The last output should be 4x10=40Chose the
correct Answer while x < 11:print(str(n)+'x'+ str(x)+'='+str(n*x))x+=1

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


if points > 500%: level= Bronze
You are developing a shopping websiteYou need to
offer customers the Bronze level if they accumulate
between 500 and 600 paints in shopping.Which code if 500 <= points <= 600: level= 'Bronze'
block should you use?Choose the correct answer

if points>= level>= 500 or points <= 600: Bronze


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

You have the following code:Code: def division(a,


try:division(2,0)except ArthimaticError as e:raise ValueError("Cannot
b):return a/bdivision (2.0)You need to add code to divide by zero.") from e
handle a division by zero exceptionWhich code should
you use?Choose the correct answer
try:division(2,0)except OverPointError as e:raise ValueError("Cannot
divide by zero.") from e

try:division(2,0)except ZeroDivisonError as e:raise ValueError("Cannot


divide by zero." from e
Evaluate the following code example, which is an
attempt to loop through and print a tuple of products by Remove the colon from the for statement
serial number:products = ("1111","2222", "3333",
"4444", "5555", "6666", "7777", "8888","9999")for
product in products:print(products[product])The code, Indent the print() statement
when run, is generating errors. Which fixes are needed
to make the code work properly and return the list of
products? (Choose two) Indent the for statement

while

31
You are writing code to have activity for every day in a
30-day program. There should be no activity on day continue
15.Using the dropdown arrows, fill in the missing
pieces to the code.
{select} dailyProgram in range(1, {select} ): 30
if dailyProgram == 15:
print("No activity on day 15")
{select} for
print(f"This is day {dailyProgram}")
else

break
Evaluate the following code:def score_adj (score,
rank):new_score = scoreif score > 3000 and rank > score1 = 3300
3:new_score += 300elif score > 2500 and rank >
2:new_score += 250else:new_score += 50return
new_scorescore1 = score_adj (3000, 3)score2 = score3 = 5300
score_adj (2000, 2)score3 = score_adj (5000,
5)print(score1, score2, score3)For each statement
regarding the results of the code, indicate a Yes if the score2 = 2250
statement is true and No if the statement is false.

for x in cities:
A developer is writing code to iterate printing cities and
state, with the end result looking like this:Orange for
FloridaOrange OhioOrange IllinoisSpringfield
FloridaSpringfield OhioSpringfield IllinoisCapitalAuburn for y in states:
FloridaAuburn OhioAuburn IllinoisThe first two lines of
code are as follows:cities = ["Orange", "Springfield",
"Auburn"]states = ["Florida", "Ohio", "Illinois"]Using the if x == "Springfield" and y = "Illinois":
dropdown arrows, complete the code necessary to
generate the above output.
cities = ["Orange", "Springfield", "Auburn"] if x = "Springfield" and "y" = "Illinois":
states = ["Florida", "Ohio", "Illinois"]
{select}
{select} for"x"
print(x, y)
{select}
print("Capital")
if "x "= "Springfield" and "y "= = "Illinois":

for y = in states:
...
A developer wants documentation for a function to
display when called upon in a print statement. Use the
dropdown menus to fill in the remainder of the code ...
necessary to generate the documentation.
def area(width, height):
area._doc_
{select} Generates the area of a rectangle {select}

totalArea = width * height


totalArea

return totalArea width


print({select})
height
You are creating an eCommerce script that accepts
input from the user and outputs the data in a comma-
delimited format.You write the following code to accept print("{0},{1}".format(item, sales))
input:item = input("Enter the item name: ")sales =
int(input("Enter the quantity: "))The output must meet
the following requirements:• Enclose strings in double print(item + ',' + sales)
quotes.• Do not enclose numbers in quotes or other
characters• Separate items by commas.You need to
print(f'"{item}",{sales}')
complete the code to meet the requirements.Which two
code segments could you use? Each correct answer
presents a complete solution (Choose 2)Note: You will print('"{0}",{1}'.format(item, sales))
receive partial credit for each correct answer.

random.randint (5, 12)


You are writing code to generate a random integer with
a minimum value of 5 and a maximum value of random.randrange(5, 11, 1)
11Which two functions should you use? Each correct
answer presents a complete solution (Choose 2)
random.randint (5, 11)

random.randrange(5, 12, 1)
Review the following code segment:product = 2n =
5while (n!= 0):product *= nprint (product)n = 1if n == 1
3:breakHow many lines of output does the code print?
2

4
A company needs help updating their file system. You
must create a simple file manipulation program that
os.path.isfile(myFile.txt'):
performs the following actionsChecks to see whether a
file existsIf the file exists, displays its contentsComplete
the code by selecting the correct code segment from print(file.read())
each drop-down listNote. You will receive partial credit
for each correct selection
import os os.path.isfile(myFile.txt'):
if {select}
file = open('myfile.txt')
{select} print(file.read())
file.close()
(0:10)
You are writing a function to read a data file and print
the results as a formatted table. You write code to read
(1:5.1f)
a line of data into a list named fields.The printout must
be formatted to meet the following requirementsFruit
name (field [0]): Left-aligned in a column 10 spaces (2:7.2f)
wide.Weight (fields[1]): Right-aligned in a column 5
spaces wide with one digit after the decimal point.Price
(fields[2]): Right aligned in a column 7 spaces wide with {10:0}
two digits after the decimal pointThe following shows a
one-line sample of the output:Oranges 5.6 1.33
print(" {select} {select} {select} ", format(fields[0], {5:1f}
eval(fields[1]), rval(field [2])))
{7:2f}
A company needs help updating its file system. You
must create a simple file-manipulation program that open('myFile.txt', 'a')
performs the following actions:• Creates a file using the
specified name.Appends the phrase "End of listing" to
the file.You need to complete the code to meet the file write
requirements.Complete the code by selecting the
correct code segment from each drop-down list.Note:
You will receive partial credit for each correct selection. open('myFile.txt')
import os
file= {select}
{select} ("End of listing") file read
file.close()
Python will not check the syntax of lines 01 through 04.
You create the following Python function to calculate
the power of a number. Line numbers are included for
reference only.# The calc_power function calculates The pound sign (#) is optional for lines 02 and 03.
exponents# x is the base#y is the exponent# The value
of x raised to the y power is returneddef calc_power(x,
y):comment = "# Return the value"return x ** y # raise x The string in line 06 will be interpreted as a comment.
to the y powerFor each statement, select True or False.

Line 07 contains an inline comment


You are writing code to create an E shape from
asterisks. You need to print five lines of code, with four
asterisks each on the first, third, and fifth lines and one 6
asterisk each on the second and fourth lines, as
shown.Complete the code by typing the correct
numbers in the boxes. Enter each number as an 5
integerNote: You will receive partial credit for each
correct entry.
result_str=""
3
for row in range(1, {select} ):
for column in range(1, {select} ): 9
if (row==1 or row==3 or row==5):
result_str=result_str+"*"
elif column==1:
result_str=result_str+"*"
result_str=result_str+"\n"
print(result_str)
You are creating an interactive Times Table Helper
program intended for elementary school children.You
need to complete a function named times_tables that
computes and displays all multiplication table results for col in range(1, 13):
from 2 to 12, as shown below:4 6 8 10 12 14 16 18 20
22 246 9 12 15 18 21 24 27 30 33 368 12 16 20 24 28
32 36 40 44 4810 15 20 25 30 35 40 45 50 55 6012 18 for row in range(2,13):
24 30 36 42 48 54 60 66 7214 21 28 35 42 49 56 63 70
77 8416 24 32 40 48 56 64 72 80 88 96
# Displays times tables 2-12
for col in range(12, 13):
def times_tables():
{select} for row in range(1,12):
{select}
print(row *col, end = "")
print()
You are writing a function that increments the player
score in a game.The function has the following To meet the requirements, you must change line 01 to def increment
requirements:• If no value is specified for points, then
points start at one.If bonus is True, then points must be score(score, bonus, points = 1):
doubled.You write the following code. Line numbers
are included for reference only.def
If you do not change line 01 and the function is called with only two
increment_score(score, bonus, points):if bonus =
True:points= points * 2score = score + pointsreturn parameters, an error occurs.
scorepoints= 5score =10new_score =
increment_score(score, True, points)For each
statement, select True or FalseNote: You will receive
Line 03 will also modify the value of the variable points declared at line
partial credit for each correct selection 06.

You need to write code that performs the following try:


tasks.Call the process() function.If the process()
function throws an error, call the logError()
function.Always call the displayResult() function after except:
calling the process() function.Complete the code by
moving the appropriate code segments from the list on
the left to the correct locations on the right. You may finally:
use each code segment once, more than once, or not
at all.
{select}
catch:
process()
{select} if
logError()
{select}
displayResult() throw:
10
You have the following code:w_list = ['dog', "bear"]x =
0for word in w_list: for i in range(len(word)): x = x + 1 if 7
x > 6: breakWhat will be the value of x?Choose the
correct answer
6

5
A bicycle company is creating a program that allows
customers to log the number of miles biked. The 01 def get_name():
program will send messages based on how many miles
the customer logs.You write the following Python code.
01 def get_name(biker):
Line numbers are included for reference only.02
name=input("What is your name? ") 03 return name
calories= miles * calories_per_milereturn 01 def get_name(name):
caloriesdistance = int(input("How many miles did you
bike this week? "))burn _rate = 50biker=
get_name()calories_burned = calc_calories (distance, 04 def calc_calories():
burn_rate)print(biker, ", you burned about",
calories_burned, " calories.")You need to define the
two required functions.Which two code segments 04 def calc_calories (miles, burn_rate):
should you use for line 01 and line 04? Each correct
answer presents part of the solution. (Choose 2.)
04 def calc_calories (miles, calories_per_mile):
if num>-10 and num
You are writing a Python program to determine if a
number (num) the user inputs is one, two, or more than
two digits (digits).Complete the code by selecting the elif num > -100 and num
correct code segment from each drop-down list.
num = int(input("Enter a number with 1 or 2 digits: "))
digits = "0" else
{select}
digits = "1"
{select}
if num 10.
digits = "2"
{select} elif num 100
digits = "2"
print(digits + " digits.")
if
You build a unit test module as shown belowimport
unittestclass
denoClass(unittest.TestCase):@unittest.skipUnless(25,
"Message 1")def test_number(self):self.assertTrue(2 >
5, "Message 1")def test number4
test_number2(self):self.fail("Message
2")self.skipTest("Message 2")def test_number3(self):if
"demo".isalpha():self.skipTest("Message test number3
3")else:[email protected]("demo".upper() !=
"DEHO", "Message 4")def
test_number4(self):self.assertEqual("DEMO".lower(),
test number2
"DEMO", "Message 4")if ___name__ ==
'__main__':unittext.main()Which two test methods will test number1
be skipped in the test results, without being counted as
a failure orsuccess? Each correct answer presents a
complete solutionChose the correct Answer:

You might also like