0% found this document useful (0 votes)
20 views8 pages

Dump 2

The document contains various programming questions and code snippets related to Python functions, exception handling, file manipulation, and data processing. It includes multiple-choice questions, code completion tasks, and true/false statements regarding code functionality and syntax. The content is aimed at assessing knowledge and skills in Python programming concepts.

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)
20 views8 pages

Dump 2

The document contains various programming questions and code snippets related to Python functions, exception handling, file manipulation, and data processing. It includes multiple-choice questions, code completion tasks, and true/false statements regarding code functionality and syntax. The content is aimed at assessing knowledge and skills in Python programming concepts.

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/ 8

Question Correct Answer

order_total = call subtotal(500,.07)


Take a look at the following function: def
subtotal(order_amt, sales_tax):subtotal =
float(order_amt) * (1 + float(sales_tax))return order_total(subtotal(500,.07))
subtotalWhich code example properly calls the
function and returns a calculation, stored in the order_total = subtotal(500,.07)
variable called order_total??

order_total = def subtotal(500, .07)


(amount, salesTaxRate):

Complete the code example to build a function that return sub


does the following:• Its name is the calcSubtotal•
The function takes an amount and a sales tax rate def calSubtotal
and calculates a subtotal• The new subtotal is
returned
{select} {select} def: calcSubtotal
subtotal = amount * (1 + salesTaxRate)
{select} return subtotal

(x, y)
[::1]
A developer needs to write code to reverse the [1::]
character output of a product code. Which variable
declaration will reverse one of the product codes?
[::-1]

[-1::]
x + y > 7 and x * y < 15
Analyze the following code:x = 5y = 3z = x + y > 7 z=
and x * y < 15 or x - y > 2Which expression is
performed last for calculating the value of z?
x - y &gt; 2

x * y &lt; 15 or x - y &gt; 2
help(Example1)
You want to load the module Example1 and display Import Example1; help (Example1)
its documentation in the Python interpreter. Which
command should you use?
import Example

руthоn -m Example1
You are working on the code shown in the answer
area. You need to evaluate each operator and a=17b=5a/b
select the one whose result is the smallest
valueWhich operator should you use? To answer,
select the appropriate option.Choose the correct a=17b=5a+b
options

a=17b=5a*b

a=17b=5a%b
def division(a, b).return
a/btry:division(4.0)division("3","4")excep
t(ZeroDivisonError,TypeError) as
e:print(f'exception caught "%s" {e}')

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

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

datetime.datetime.strftime()
The proper syntax for pydoc is Python -m
pydoc module where module represents
the name of a Python module.
For each of the statements regarding pydoc, select
true if the statement is true and No if the statement
is false. Pydoc is a self-contained executable that
can be run from a command-line prompt.

Pydoc generates documentation on Python


modules.
You are in the process of writing some code to float
divide two numbers. You want the result to display
so long as there are no errors. If there are errors,
you want to display a message indicating that the shuffle ()
user either tried to divide by zero or used an invalid
number.Using the dropdown arrows, fill in the except
missing keywords to make this happen.
a = float(input("Enter a number. "))
b = float(input("Enter a number to divide by. ")) try
{select}
print (f"The answer is {a/b}.") def
{select}
print("This did not work. Did you try to divide by
zero?") zero
while

31
You are writing code to have activity for every day
in a 30-day program. There should be no activity
on day 15.Using the dropdown arrows, fill in the continue
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
You are writing code to list cities and then delete,
from the list, any city that has more than five letters len
in the name.Using the dropdown arrows, fill in the
missing pieces of code needed to complete the switch
code needed to fulfill this task.
cities = ['Anchorage', 'Juneau', 'Fairbanks',
'Ketchikan', 'Sitka', 'Wasilla'] cities
for city in cities:
if {select} (city) >; 5: remove
cities, {select} (city)
os

You are in the process of writing code to delete a request


file if it exists or just display a message indicating
that there was no file to remove if the file does not
exist.Using the dropdown arrows, select the proper isfile
code pieces to finish this code example.
import {select} isexist
if os.path.{select} ('results.txt'):
os.{select} ('results.txt')
print("The results file has been removed.") remove
else:
print("There was no results file to remove.") choice

push
Choose the correct lines of code to satisfy the
needs of the following function:Students with
score >= 90:
scores of 90 or higher get an A.Students with
scores from 80 to 89 get a B.Students with scores score
from 70 to 79 get a C.Everyone else gets an F.
def grade(score):
if {select} score
grade = "A"
elif {select} score >= 70;
grade = "B"
elif {select}
grade = "C" grade = F:
else:
{select} grade = "F"
return grade

score >= 80

score == 70
Using the dropdown arrows for the missing code
pieces, complete the following code example so
that it accomplishes the functionality of this game:A
user gets five chances to correctly guess a whole
number from 1 to 10. If the user guesses correctly, from random import randint
they get a congratulatory message and the game
ends. If not, they get a message thanking them for
playing. from random import rand
{select} rand(1,10)
for i in range (5):
guess int(input("Enter a number from 1 to 10. "))
randNum = {select} randint(1,10)
if guess == randNum:
print("We matched!")
break
else: print("We did not match. Try again")
max
You have daily attendance figures for a conference min
and want to know the highest attendance for the
conference and the lowest attendance for the
conference.Using the dropdown arrows, fill in the {max}
missing code pieces necessary to obtain those
amounts. {min}
attendance [300, 250, 200, 400, 150, 225,325]
print ({select} (attendance))
print({select} (attendance)) min

max
You find errors while evaluating the following code. while (index
Line numbers are included for reference
only.numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]index =
0while (index < 10)print(numbers [index])if
if numbers [index] == 6;
numbers(index) = 6breakelse:index x+=1
Which code segment should you use at line 03? while (index
{select}
Which code segment should you use at line 06? if numbers [index] >= 6;
{select}
import

unittest. TestCase
You need to test whether an object is an instance
of a specific class.How should you set up the unit test isInstance(self)
test?Complete the code by selecting the correct
option from each drop-down list.Note: You will
receive partial credit for each correct selection. self assertisinstance(obj, cls, msg=None)
{select} unittest
class TestIsInstance( {select} ): export
def {select}:
{select}
if__name__ == '__main__': unittest. TestInstance
unittest.main()
test isInstance(test)

if
while

if
You are writing code to meet the following
requirementsAllow users to ropeuledly enter in
words.Output the number of characters in each
wordComplete the code by selecting the correct
option from each drop-downlistNote: You will while
receive partist credit for each correct selection
x = "Hello" if
{select} x != "QILI":
num = 0
{select} char {select} x: in
num +=1
print (num) while
x = input("Enter new word of Qull to exit: ")
if

in
Bread
The Script.py file contains the followingcodeimport
sysprint(sys.argv[2])You run the following Cheese
command:python Script.py Cheese Bacon
BreadWhat is the output of the command? Script.py

Bacon
You are writing a function to read a data file and
print the results as a formatted table. You write (0:10)
code to read a line of data into a list named
fields.The printout must be formatted to meet the
following requirementsFruit name (field [0]): Left- (1:5.1f)
aligned in a column 10 spaces wide.Weight
(fields[1]): Right-aligned in a column 5 spaces wide
with one digit after the decimal point.Price (2:7.2f)
(fields[2]): Right aligned in a column 7 spaces wide
with two digits after the decimal pointThe following {10:0}
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}
Returns the current balance of the bank
accountdef get_balance():return balance

def get_balance():/*Returns the current


A bank is migrating their legacy bank transaction
balance of the bank account */return
code to Python.The bank hires you to document balance
the migrated code.Which documentation syntax is
correct? // Returns the current balance of the bank
accountdef get_balance():return balance

def get_balance():#Returns the current


balance of the bank account return
balance
You are writing a function to perform sate division
of numbers.You need to ensure that a denominator if numorator is None or denominator is
and numerator are passed to the function and that None:
the denominator is not zeroComplete the code by
selecting the correct code segment from each
drop-down list elif denominator == 0
def safe_divide(numerator, denominator):
{select} if numorator is None or denominator is
print("A required value is missing.")
{select} None:
print("The denominator is zero.")
else: elif denominator == 0
return numerator/ denominator
A file named python.txt is created if it
Review the following code segmentf does not exist
=open("python.txt", "a")f.write("This is a line of
text.")f.close()For each statement about the code The data in the file will be overwritten
segment, select True of False
Other code can open the file alter this code
runs
You work on a team that is developing a game.You
need to write code that generates a random from random import randrange
number that meets the following requirements:• print(randrange(0, 100, 5))
The number is a multiple of 5.• The lowest number
is 5.• The highest number is 100.Which two code
segments will meet the requirements? Each correct from random import randint
answer presents a complete solution.(Choose
2.)Note: You will receive partial credit for each
print(randint(1, 20) * 5)
correct answer.
from random import randrange
print(randrange(5, 105, 5))

from random import randint


print(randint(0, 20) * 5)
You are writing a function that increments the
player score in a game.The function has the To meet the requirements, you must
following requirements:If no value is specified for change line 01 to: def
points, then points start at one If bonus is True, increment_score(score, bonus, points = 1):
then points must be doubled.You write the
following code. Line numbers are included for
reference only.def increment_score (score, bonus, If you do not change line 01 and the
points):if bonus == True:return scorepointspoints * function is called with only two
2score = score + pointspoints = 5score =
10new_score = increment_score (score, True, parameters, an error occurs.
points)For each statement, select True or
FalseNote: You will receive partial credit for each Line 03 will also modify the value of the
correct selection. variable points declared at line 06.
A company needs help updating their file system.
You must create a simple file-manipulation
program that performs the following actions:• os path isfile('myFile txt')
Checks to see whether a file exists.• If the file
exists, displays its contents.Complete the code by
selecting the correct code segment from each print(file.read())
drop-down listNote: You will receive partial credit
for each correct selection. os path isfile ("myFile.txt")
import os
if {select} :
file open(myFile.txt') print()
{select}
file.close()
You are writing a function that increments the
player score in a game.The function has the To meet the requirements, you must
following requirements:• If no value is specified for change line 01 to def increment
points, then points start at one.If bonus is True, score(score, bonus, points = 1):
then points must be doubled.You write the
following code. Line numbers are included for
reference only.def increment_score(score, bonus, If you do not change line 01 and the
points):if bonus = True:points= points * 2score = function is called with only two
score + pointsreturn scorepoints= 5score
=10new_score = increment_score(score, True,
parameters, an error occurs.
points)For each statement, select True or
FalseNote: You will receive partial credit for each Line 03 will also modify the value of the
correct selection variable points declared at line 06.
Review the following program. Line numbers are
for reference only.def petStore (category, species, The function returns a value
breed="none"):print(f"\nYou have selected an
animal from the {category) category."if breed ==
"none":print (f"The {category} you selected is a The function calls at lines 12 and 15 are
{species}.")else:print(f"The {category) you selected
is a {species} {breed)")category = input("Enter dog,
valid.
cat, or bird:")species input("Enter species:")if
category == "dog" or category == The function calls at lines 14 and 16 will
"cat":breed=input("Enter breed:")petStore(category, result in an error.
species, breed)else:petStore (category,
species)petStore (breed="Maltese",
species="Canine", category="dog")petStore("bird",
species="Scarlet Macaw")For each statement
about the program, select True or FalseNote: You
will receive partial credit for each correct selection.

You are writing a program to display special offers


for My Healthy Eats Delivery. Line numbers are for
reference only.Complete the code in lines 04, 05,
and 15 by selecting the correct option from each
drop-down list.import
datetimedailySpecials=("Spaghetti", "Macaroni &
Cheese", "Meatloaf", "Fried now=datetime.date()
ChickenweekendSpecials=("Lobster", "Prime Rib",
"Parmesan-Crusted Cod")print("My Healthy Eats today=now.starttime("%A")
Delivery")if today == "Friday" or today =-"Saturday"
or today =="Sunday":print("The weekend specials
include:")for item in daysLeft=6-now.weekday()
weekendSpecials:print(item)else:print("The
weekday specials include: ")for item in now=time.date()
dailySpecials:print(item)print (f"Pricing specials
change in {daysLeft} days")Complete the code in
lines 04, 05 and 15 by selecting the correct option today=starttime("A")
from each drop-down list.
In line 04, retrieve the current date daysLeft=now.weekday-weekday()
{select}
In line 05, retrieve the weekday
{select}
In line 15, calculate the number of days left in the
week
{select}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy