PYTHON CERTIFICATION EXAM REVIEWER

0.0(0)
Studied by 0 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/75

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 6:32 PM on 7/4/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

76 Terms

1
New cards

Good luck sa retake bukas! Review lang, stay calm, at tiwala sa pinag-aralan. Kaya natin 'to. Certified Pythonista soon! 🐍💯

Good luck sa retake bukas! Review lang, stay calm, at tiwala sa pinag-aralan. Kaya natin 'to. Certified Pythonista soon! 🐍💯

2
New cards

Evaluate the following Python arithmetic expression:

(3*(1+2)*2 - (2*2)*3)

What is the result?

Answer Area

A. 3

B. 13

C. 15

D. 69

C. 15

--------------------------------------------------------------------------

✅ Why C is Correct

Follow Python's Order of Operations (PEMDAS):

Parentheses → Exponents → Multiplication/Division → Addition/Subtraction

Step-by-step evaluation:

(1+2) = 3

3 ** 2 = 9

3 * 9 = 27

(2 ** 2) = 4

4 * 3 = 12

27 - 12 = 15

❌ Why the Other Options Are Incorrect

A. 3

This would only be correct if you incorrectly simplified the entire expression as if only the subtraction mattered or ignored most of the operations.

B. 13

This could be chosen if you misapplied the order of operations, possibly doing subtraction before multiplication.

D. 69

This would be the result if you incorrectly performed operations left-to-right without respecting exponent precedence.

🔄 When the Other Choices Could Be Correct

A. 3

Would be correct if the expression was simply (27 - 24) instead of the given one.

B. 13

Would be correct if the last multiplication was wrongly computed as 4*... or if a typo in the original problem changed the numbers.

D. 69

Would be correct if the expression was written as (3 (1 + 2) 2**2 - 3) (multiplying all terms directly rather than squaring first).

3
New cards

Northwind Traders has hired you as an intern on the coding team that creates e

commerce applications.

You must write a script that asks the user for a value. The value must be used as a

whole number in a calculation, even if the user enters a decimal value.

You need to write the code to meet the requirements.

Which code segment should you use?

Answer Area

A. totalltems = int(input("How many items would you like?"))

B. totalltems = str(input("How many items would you like?"))

C. totalltems = float(input("How many items would you like?"))

D. totalltems = input("How many items would you like?")

A. totalltems = int(input("How many items would you like?"))

--------------------------------------------------------------------------

✅ Why A is Correct

input() always returns a string by default.

int() converts the user's input to an integer, ensuring it is treated as a whole number in calculations.

Even if the user enters a decimal like 4.9, Python will throw an error unless they enter a whole number — which is correct because the requirement specifies whole numbers only.

❌ Why the Other Options Are Incorrect

B. str(input(...))

Converts input to a string explicitly, but it's already a string by default. Cannot be used in arithmetic calculations directly.

C. float(input(...))

Accepts decimal values, which violates the requirement for whole numbers.

D. input(...)

Leaves the input as a string, which will cause a TypeError if used in mathematical calculations without conversion.

🔄 When the Other Choices Could Be Correct

B. str(...)

Correct only if you were planning to work with text values (e.g., printing or concatenating user input, not doing math).

C. float(...)

Correct if you needed to perform decimal-based calculations, like prices or weights.

D. input(...)

Correct only if you intended to treat the input as raw text, not for calculations.

4
New cards

You are creating a Python program that shows a congratulation message to employees on their service anniversary. You need to calculate the number of years of service and print a congratulatory message. You have written the following code. Line numbers are included for reference only.

01 start = input("How old were you on your start date?)

02 end = input('How old are you today?")

03

You need to complete the program.

Which code should you use at line 03?

Answer Area

A. print("congratulations on " + int(end - start) + " years of service!")

B. print("congratulations on " + (int(end) - int(start)) + " years of service!")

C. print("congratulations on " + str(end - start) + " years of service!")

D. print("congratulations on " + str(int(end) - int(start)) + " years of service!")

D. print("congratulations on " + str(int(end) - int(start)) + " years of service!")

--------------------------------------------------------------------------

✅ Why D is Correct

input() returns strings by default.

You must convert start and end to integers using int() before performing subtraction.

After calculating (int(end) - int(start)), you must convert the result back to a string using str() for concatenation with other text in print().

❌ Why the Other Options Are Incorrect

A. int(end - start)

Tries to subtract two strings (end - start), which will raise a TypeError. You must convert before subtraction.

B. (int(end) - int(start))

Correct calculation but missing str() for concatenation. Python cannot concatenate an integer directly with strings.

C. str(end - start)

Attempts subtraction on strings before conversion, causing a TypeError.

🔄 When the Other Choices Could Be Correct

A. int(end - start)

Would work only if end and start were already integers (e.g., if you used start = int(input(...)) earlier).

B. (int(end) - int(start))

Would work if you used a comma in print() instead of concatenation:print("congratulations on", int(end) - int(start), "years of service!").

C. str(end - start)

Would work if end and start were already integers, but still logically incorrect because end - start must be done numerically, not as strings.

5
New cards

You develop a Python application for your company.

You want to add notes to your code so other team members will understand it

What should you do?

Answer Area

A. Place the notes after the last line of code separated by a blank line.

B. Place the notes inside of parentheses on any line.

C. Place the notes after the # sign on any line.

D. Place the notes before the first line of code separated by a blank line.

C. Place the notes after the # sign on any line.

--------------------------------------------------------------------------

✅ Why C is Correct

In Python, comments are written using the # symbol.

Anything after # on the same line is ignored by Python and serves as a note for humans reading the code.

Comments can be placed on their own line or after code on the same line.

❌ Why the Other Options Are Incorrect

A. Place the notes after the last line of code separated by a blank line.

While you can add notes at the end of the file, this is not the standard method for commenting throughout the code. It doesn't fulfill the requirement of making the code understandable line by line.

B. Place the notes inside of parentheses on any line.

Parentheses are used for function calls, grouping expressions, or tuples—not for comments. Text in parentheses will be executed or cause a syntax error if not valid.

D. Place the notes before the first line of code separated by a blank line.

Comments can be placed at the beginning of a file, but the requirement is to add notes to the code, not just at the top.

🔄 When the Other Choices Could Be Correct

A. Useful for adding a general note or license information after all code, but not for inline explanations.

B. Never correct—Python does not treat text in parentheses as comments.

D. Commonly used for file-level documentation (e.g., purpose of the script), but not for explaining specific lines.

6
New cards

You are writing an application that uses the sqrt function. The program must reference the function using the name squareRoot. You need to import the function. Which code segment should you use?

Answer Area

A. from math import sqrt as squareRoot

B. from math.sqrt as squareRoot

C. import math.sqrt as squareRoot

D. import sqrt from math as squareRoot

A. from math import sqrt as squareRoot

--------------------------------------------------------------------------

✅ Why A is Correct

from math import sqrt as squareRoot correctly imports the sqrt function directly from the math module and renames it to squareRoot using the as keyword.

After this import, you can call it simply as:squareRoot(16) → 4.0

❌ Why the Other Options Are Incorrect

B. from math.sqrt as squareRoot

Wrong syntax. You cannot use from directly on a function. The from keyword works only with modules/packages, not with a specific function path like math.sqrt.

C. import math.sqrt as squareRoot

import works only for modules, not for functions. You would need to import the entire math module (import math) and call the function as math.sqrt(). You can't alias a function directly this way.

D. import sqrt from math as squareRoot

Incorrect syntax. Python does not support the reversed order of import sqrt from math. The correct structure is from module import function.

🔄 When the Other Choices Could Be Correct

B. Never valid—Python syntax does not allow this.

C. Would work if you wrote import math (without aliasing), but then you'd have to call it as math.sqrt(), not squareRoot().

D. Never valid—Python import statements never use this syntax.

7
New cards

This question requires that you evaluate the underlined text to determine if it is

correct. You write the following code:

import sys

try:

file_in = open("in.txt", 'r')

file_out = open("out.txt", 'w+')

except lOError:

print('cannot open', file_name)

else:

i = 1

for line in file_in:

print(line. rstrip())

file_out.write("line " + str(i) + ": " + line)

i = i + 1

file_in.close()

file_out.close ()

The out.txt file does not exist. You run the code. The code will execute without error. Review the underlined text. If it makes the statement correct, select "No change is needed." If the statement is incorrect, select the answer choice that makes the statement correct.

Answer Area

A. No change is needed.

B. The code runs, but generates a logic error.

C. The code will generate a runtime error.

D. The code will generate a syntax error.

A. No change is needed.

--------------------------------------------------------------------------

✅ Why A is Correct

The mode 'w+' in open("out.txt", 'w+') creates the file if it does not exist.

The try-except block handles potential file errors, but since 'w+' ensures file creation, no error occurs.

Python automatically writes to out.txt and prints each line from in.txt as intended.

❌ Why the Other Options Are Incorrect

B. The code runs, but generates a logic error

There's no logic error here; it properly reads from in.txt and writes to out.txt. A logic error would occur if, for example, it wrote incorrect data or missed a line, which isn't the case.

C. The code will generate a runtime error

No runtime error because open() with 'w+' will not fail due to a missing file.

A runtime error could happen if in.txt does not exist, but the question specifically concerns out.txt.

D. The code will generate a syntax error

The code syntax is valid. No misplaced colons, incorrect indentation, or keyword misuse.

🔄 When the Other Choices Could Be Correct

B. Logic Error

Would apply if i wasn't incremented properly or if the program didn't correctly write to out.txt.

C. Runtime Error

Would occur if in.txt does not exist or if there were a permission issue when opening files.

D. Syntax Error

Would occur if, for example, print(line. rstrip()) had incorrect spacing (line.rstrip() is proper syntax), or if indentation was broken.

8
New cards

The file contains sales from the previous day, including the item id, price, and quantity. The following shows a sample of data from the file:

10, 200, 5

20, 100, 1

The code must meet the following requirements:

. Each line of the file must be read and printed

. If a blank line is encountered, it must be ignored

. When all lines have been read, the file must be closed

You create the following code. Line numbers are included for reference only.

01 inventory = open("inventory.txt", 'r')

02 eof = False

03 while eof == False:

04 line = inventory.readline()

05

06

07 print(line)

08 else:

09 print ("End of file")

10 eof = True

11 inventory,close()

Which code should you write for line O5 and line 06?

Answer Area

A.

05 if line != '':

06 if line !="":

B.

05 if line != '\n':

06 if line != None:

C.

05 if line != '\n':

06 if line != "":

D.

05 if line != '':

06 if line != "\n":

D.

05 if line != '':

06 if line != "\n":

--------------------------------------------------------------------------

✅ Why D is Correct

line != '' checks for an empty string, which occurs at EOF (end of file).

line != '\n' ensures blank lines (only newline characters) are ignored.

This combination satisfies both requirements: skip blank lines and detect end-of-file properly.

❌ Why the Other Options Are Incorrect

A. if line != '' and if line != ""

Redundant check ('' and "" are the same).

Does not skip blank lines with \n; it only detects EOF.

B. if line != '\n' and if line != None

readline() never returns None; it returns '' at EOF.

So line != None will always be True, causing an infinite loop.

C. if line != '\n' and if line != ""

Checks blank lines correctly (\n) but does not properly detect EOF first.

Needs to check for '' before processing, otherwise it might still process after EOF.

🔄 When the Other Choices Could Be Correct

A. Could be valid only if you don't care about blank lines (just reading until EOF).

B. Would be correct in a hypothetical API where readline() returns None at EOF (not true in Python).

C. Works if placed in a for line in file: loop because the loop stops at EOF automatically, making '' unnecessary.

9
New cards

Tailspin Toys uses Python to control its new toy Happy Clown. The program has errors that cause the clown to run around in an infinite circle. You have been hired to help debug the following Happy Clown code. Line numbers are included for reference only.

01 import math

02 #default motion for happy clown

03 power = True

04 move = 0

05 while(power):

06 if move == 0:

07 turnValue = math.pi/move

08 move+=5

09 else:

10 turnValue = 0

11 move = 0

Which error exists in the code?

Answer Area

A. Line 05 has a syntax error because it should read (power == True).

B. Line 08 has a syntax error because + = is an invalid statement.

C. Line 07 causes a runtime error due to division by zero.

D. Line 05 causes a runtime error because the expression is incomplete.

C. Line 07 causes a runtime error due to division by zero.

--------------------------------------------------------------------------

✅ Why C is Correct

At program start:

move = 0 (line 04).

The while(power) loop executes.

The condition if move == 0: (line 06) is True on first run.

Line 07: turnValue = math.pi / move → becomes math.pi / 0, causing a ZeroDivisionError (runtime error).

❌ Why the Other Options Are Incorrect

A. Line 05 has a syntax error because it should read (power == True).

Wrong. while(power): is perfectly valid; Python treats any nonzero/non-None value (True here) as a truthy condition.

B. Line 08 has a syntax error because + = is an invalid statement.

Wrong. The operator is += (no space), which is valid syntax in Python (move += 5).

D. Line 05 causes a runtime error because the expression is incomplete.

Wrong. while(power): is a complete and valid loop condition.

🔄 When the Other Choices Could Be Correct

A. Would only be correct in languages like C++/Java that don't allow implicit boolean evaluation, but not in Python.

B. Would be correct only if written incorrectly as move + = 5 (with a space).

D. Could be correct if the line were written incorrectly as while power (missing the colon :), which would cause a syntax error.

10
New cards

Woodgrove Bank is migrating their legacy bank transaction code to Python.

You have been hired to document the migrated code.

Which documentation syntax is correct?

Answer Area

A. Returns the current balance of the bank account

def get_balance():

return balance

B. def get_balance():

/Returns the current balance of the bank account/

return balance

C. //Returns the current balance of the bank account

def get_balance():

return balance

D. def get_balance():

#Returns the current balance of the bank account

return balance

D. def get_balance():

#Returns the current balance of the bank account

return balance

--------------------------------------------------------------------------

✅ Why D is Correct

Python uses the # symbol for single-line comments.

#Returns the current balance of the bank account is the correct way to document a line of code in Python.

❌ Why the Other Options Are Incorrect

A. Returns the current balance of the bank account (before def)

Incorrect because it's just plain text, not valid Python syntax. Python would throw a syntax error if text appears outside a comment or string.

B. /Returns the current balance of the bank account/

Incorrect because / ... / is C/Java-style commenting, not valid in Python.

C. //Returns the current balance of the bank account

Incorrect because // is used in languages like Java, C++, and JavaScript, not Python. In Python, // is a floor division operator, not a comment marker.

🔄 When the Other Choices Could Be Correct

A would be correct if rewritten as a docstring:

def get_balance(): """Returns the current balance of the bank account""" return balance

B would be correct in C, C++, or Java, where block comments are allowed.

C would be correct in Java, JavaScript, or C++, where // starts a single-line comment.

11
New cards

You develop a Python application for your company.

You need to accept input from the user and print that information to the user screen. You have started with the following code. Line numbers are included for reference only.

01 print("What is your name?")

02

03 print(name)

Which code should you write at line 02?

Answer Area

A. name = input

B. input(name)

C. name = input()

D. input("name")

C. name = input()

--------------------------------------------------------------------------

✅ Why C is Correct

input() reads user input from the console and returns it as a string.

Assigning it to name (name = input()) stores the user's response for later use in print(name).

❌ Why the Other Options Are Incorrect

A. name = input

Incorrect because it assigns the input function itself to name, not the user's input.

print(name) would print something like .

B. input(name)

Incorrect because name is undefined at this point. Passing it as an argument will cause a NameError.

Correct usage would require a string prompt, not a variable.

D. input("name")

Incorrect because this only prompts the user with the literal text "name" but does not store the input.

Without assignment (name = input("name")), you can't use the value later.

🔄 When the Other Choices Could Be Correct

A → Never correct for taking input. Only used if you intend to reference the function itself (rare).

B → Correct if modified to name = input("What is your name?").

D → Correct if modified to name = input("name") (still odd as a prompt but would work if assigned).

12
New cards

You develop a Python application for your school.

You need to read and write data to a text file. If the file does not exist it must be created.

If the file has content the content must be removed.

Which code should you use?

Answer Area

A. open("local_data", "r+")

B. open("local_data", "w+")

C. open("local_data", "r")

D. open("local_data", "w")

B. open("local_data", "w+")

--------------------------------------------------------------------------

✅ Why B is Correct

"w+" mode:

Opens the file for both reading and writing.

Creates the file if it does not exist.

Truncates (clears) the file if it already exists, ensuring old content is removed.

This exactly matches the requirements.

❌ Why the Other Options Are Incorrect

A. open("local_data", "r+")

Fails if the file does not exist (r+ requires the file to exist).

Does not automatically clear existing content unless you manually truncate.

C. open("local_data", "r")

Read-only mode.

Cannot write to the file and fails if the file does not exist.

D. open("local_data", "w")

Write-only mode.

Creates the file and truncates it, but does not allow reading, violating the requirement.

🔄 When the Other Choices Could Be Correct

A (r+) → Use when you need to read and write without deleting existing content.

C (r) → Use when you only need to read and the file already exists.

D (w) → Use when you only need to write, and you want to clear/create the file.

13
New cards

You evaluate the following code:

numList = [0,1,2,3,4]

print(5 in numList)

What is the output of the print statement?

Answer Area

A. 4

B. False

C. True

D. 5

B. False

--------------------------------------------------------------------------

✅ Why B is Correct

The expression 5 in numList checks if the value 5 exists in the list [0,1,2,3,4].

Since 5 is not in the list, the result is False.

❌ Why the Other Options Are Incorrect

A. 4

The expression does not return a list index or a value from the list—it only checks for membership.

C. True

Would be correct only if 5 was present in the list.

D. 5

The statement does not print the searched value; it prints a Boolean (True or False).

🔄 When the Other Choices Could Be Correct

A (4) → If you used print(numList[4]), it would print 4.

C (True) → If the list were [0,1,2,3,4,5], print(5 in numList) would print True.

D (5) → If you explicitly printed 5, e.g., print(5), not with the in operator.

14
New cards

A classmate has asked you to debug the following code:

x = 4

while x >= 1:

if x % 4 == 0:

print ("party")

elif x - 2 < 0:

print("cake")

elif x / 3 == 0:

print("greeting")

else:

print("birthday")

x = x - 1

What is the output that is printed to the screen?

Answer Area

A. birthday

party

greeting

cake

B. party

birthday

birthday

cake

C. party

greeting

birthday

cake

D. birthday

greeting

party

cake

B. party

birthday

birthday

cake

--------------------------------------------------------------------------

✅ Why B is Correct

We trace the loop step by step:

x = 4 → 4 % 4 == 0 ✅ → prints "party"

x = 3 → 3 % 4 != 0, 3 - 2 < 0 ❌, 3 / 3 == 0 ❌ (since 3/3 = 1), so else → "birthday"

x = 2 → 2 % 4 != 0, 2 - 2 < 0 ❌, 2 / 3 == 0 ❌ (0.66 ≠ 0), so else → "birthday"

x = 1 → 1 % 4 != 0, 1 - 2 < 0 ✅ → prints "cake"

Loop ends after x = 0.

❌ Why the Other Options Are Incorrect

A. birthday → party → greeting → cake

Order is wrong; the first output is definitely "party".

"greeting" never prints because x / 3 == 0 is never true for positive integers.

C. party → greeting → birthday → cake

Same reason: "greeting" never prints.

D. birthday → greeting → party → cake

Wrong order; the first output is "party", not "birthday".

🔄 When the Other Choices Could Be Correct

A → If you initialized x = 1 (so "birthday" prints first), modified logic to allow x/3==0 for some negative or zero value, and reordered.

C → If you mistakenly wrote x // 3 == 0 (floor division), "greeting" would print for x = 1 or 2.

D → If you started with x = 1 and altered the first condition.

15
New cards

You write the following code:

list_1 = [1, 2]

list_2 = [3, 4]

list_3 = list_1 + list_2

list_4 = list_3 * 3

print(list_4)

You run the code.

What is the output value?

Answer Area

A. [3, 6, 9, 12]

B. [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

C. [[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]

D. [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

B. [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

--------------------------------------------------------------------------

✅ Why B is Correct

list_3 = list_1 + list_2 → Concatenates two lists → [1, 2, 3, 4].

list_4 = list_3 * 3 → List repetition (not multiplication of numbers) → repeats the list 3 times →[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4].

Printing outputs the full repeated list.

❌ Why the Other Options Are Incorrect

A. [3, 6, 9, 12]

This would require multiplying each element individually ([x*3 for x in list_3]), not repeating the list.

C. [[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]

This would occur if list_3 were defined as [[1, 2], [3, 4]], not via concatenation.

D. [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

This would occur if you wrapped list_3 in another list before multiplying ([list_3] * 3).

🔄 When the Other Choices Could Be Correct

A → If you used list comprehension: list_4 = [x*3 for x in list_3].

C → If you set list_3 = [list_1, list_2].

D → If you wrote list_4 = [list_3] * 3.

16
New cards

You are writing a Python application for a dance studio.

The studio wants to encourage youth and seniors to sign up. Minors and seniors must

receive a 10% discount.

You write the following code. Line numbers are included for reference only.

01 def get_discount(minor, senior):

02 discount = .1

03

04

discount = 0

05 return discount

You need to complete the code.

Which code should you add on line 03?

Answer Area

A. if not (minor and senior):

B. if not (minor or senior):

C. if (not minor) and senior:

D. if (not minor) or senior:

A. if not (minor and senior):

--------------------------------------------------------------------------

✅ Why A is Correct

Logic Required:

Minors (minor=True) or seniors (senior=True) get a 10% discount.

Everyone else gets 0.

How the code works:

Line 02 initially assumes a discount (discount = .1).

At line 03, we only change the discount to 0 if the person is not a minor and not a senior.

not (minor and senior) correctly evaluates to True when both are False.

Example:

minor=True, senior=False → keeps 10% discount.

minor=False, senior=False → not(False and False) → True → discount set to 0.

❌ Why the Other Options Are Incorrect

B. if not (minor or senior):

Would also work logically, but it's not aligned with the structure of the given code, which assumes .1 by default and only sets 0 when both are false.

Actually, not (minor or senior) is logically equivalent to not minor and not senior—so it could work, but the intended pattern uses and.

C. if (not minor) and senior:

This incorrectly removes the discount for minors and gives 0% discount when the person is not a minor but is a senior, which contradicts the requirement.

D. if (not minor) or senior:

This would set discount = 0 for seniors, which is wrong.

🔄 When the Other Choices Could Be Correct

B → Would also produce correct logic; it's just a different equivalent form.

C → Would only be correct if only seniors who are not minors were supposed to pay full price (not the case).

D → Never correct for this scenario because seniors should always get a discount.

17
New cards

You develop a Python application for your school.

A list named colors contains 200 colors. You need to slice the list to display every other

color starting with the second color.

Which code should you use?

Answer Area

A. colors[1:2]

B. colors [::2]

C. colors[2:2]

D. colors [1::2]

D. colors [1::2]

--------------------------------------------------------------------------

✅ Why D is Correct

Requirement Breakdown:

Start from the second color → index 1 (Python lists are 0-based).

Every other color → step of 2.

Syntax Explanation:

colors[start:stop:step]

1 = start from the second element.

::2 = take every second element until the end.

Combined → colors[1::2].

Example:

colors = ['red','blue','green','yellow','pink'] print(colors[1::2]) → ['blue','yellow'] (2nd and 4th colors)

❌ Why the Other Options Are Incorrect

A. colors[1:2]

Only retrieves one element (index 1). It does not continue every other color.

B. colors[::2]

Starts from index 0, so it gets the first, third, fifth... colors. Not what was asked.

C. colors[2:2]

Produces an empty list because the start and stop indices are the same.

🔄 When the Other Choices Could Be Correct

A → If you only needed the single second color.

B → If you wanted every other color starting with the first color.

C → Rarely useful, only in very specific edge cases where you need an empty slice.

18
New cards

You write the following code:

import datetime

d = datetime.datetime(2017, 4, 7)

print('{:%B-%d-%y}' .format(d))

num=1234567.890

print('{:, .4f}' .format(num))

You run the program.

What is the output?

Answer Area

A.

2017--April--07

1,234,567.890

Press any key to continue...

B.

Apr--07--2017

1,234,567,8900

Press any key to continue...

C.

April--07--17

1,234,567.8900

Press any key to continue...

D.

April--07--17

1234567.89

Press any key to continue...

C.

April--07--17

1,234,567.8900

Press any key to continue...

--------------------------------------------------------------------------

✅ Why C is Correct

Date Formatting

%B → Full month name → April

%d → Day (two digits) → 07

%y → 2-digit year → 17

Combined: April--07--17

Number Formatting

:, → Adds comma as thousand separator → 1,234,567

.4f → 4 decimal places → 8900 (Python pads zeros)

Combined: 1,234,567.8900

❌ Why the Other Options Are Incorrect

A. 2017--April--07

Incorrect because %B-%d-%y places month first and uses 2-digit year, not full year.

B. Apr--07--2017

%B gives full month name (April), not abbreviated (Apr).

%y gives 2-digit year (17), not full year (2017).

Number formatting shows incorrect 4-decimal padding.

D. April--07--17 / 1234567.89

The number is missing both the comma separator and the required 4 decimal places.

🔄 When the Other Choices Could Be Correct

A → Would be correct if you used "%Y--%B--%d".

B → Would be correct if you used "%b--%d--%Y" and formatted without .4f.

D → Would be correct if you formatted the number as "{:.2f}" or without a comma.

19
New cards

You develop a Python application for your company.

You have the following code. Line numbers are ¡included for reference only.

01 def main(a,b,c,d):

02 value = a+b*c-d

03 return value

Use the drop-down menus to select the answer choice that answers each question based

on the information presented in the code segment.

Answer Area

Which part of the expression will be evaluated first? [1]

Which operation will be evaluated second? [2]

Which expression is equivalent to the expression in the function? [3]

[1] A. a+b || B. b*c || C. c-d

[2] A. addition || B. subtraction

[3] A. (a+b) (c-d) || B. (a + (bc)) - d || C. a + ((b*c) - d)

[1] B. b*c

[2] A. addition

[3] B. (a + (b*c)) - d

--------------------------------------------------------------------------

✅ Why These Are Correct

Order of Operations (PEMDAS in Python)

Multiplication and division are evaluated before addition and subtraction.

So, b * c is evaluated first.

After that, addition (a + (b*c)) is evaluated second.

Finally, subtraction (- d) is evaluated last.

Equivalent Expression

Writing with parentheses for clarity: (a + (b*c)) - d exactly mirrors Python's order of operations.

❌ Why the Other Choices Are Incorrect

[1] A. a+b - Addition is evaluated after multiplication.

[1] C. c-d - Subtraction occurs last, not first.

[2] B. subtraction - Subtraction is performed last, not second.

[3] A. (a+b) * (c-d) - Completely different grouping; changes the logic.

[3] C. a + ((bc) - d) - While mathematically equivalent, it implies subtraction happens immediately after multiplication, but Python performs a + (bc) first, then subtracts d.

🔄 When the Other Choices Could Be Correct

C. a + ((bc) - d) → Would be correct if you rewrote the code as value = a + (bc - d) explicitly.

A. (a+b) (c-d) → Would be correct if the code used parentheses: value = (a+b) (c-d).

20
New cards

You create the following program to locate a conference room and display the room

name. Line numbers are included for reference only.

01 rooms = {1: 'Foyer', 2: 'conference Room'}

02 room = input('Enter the room number: ')

03 if not room in rooms:

04 print('Room does not exist.')

05 else:

06 print("The room name is " + rooms[room])

Colleagues report that the program sometimes produces incorrect results.

You need to troubleshoot the program. Use the drop-down menus to select the answer

choice mat answers each question based on the information presented in the code

segment.

Answer Area

Which two data types are stored in the rooms list at line 01? [1]

What is the data type of room at line 02? [2]

Why does line 03 fail to find the rooms? [3]

[1] A. bool and string || B. float and bool || C. int and string

[2] A. bool || B. float || C. int || D. string

[3] A. Invalid syntax || B. Mismatched data type(s)

[1]C. int and string

[2]D. string

[3]B. Mismatched data type(s)

--------------------------------------------------------------------------

✅ Explanation

Why the Correct Answers Are Right

[1] int and string: The dictionary keys are integers (1, 2), and the values are strings ('Foyer', 'Conference Room').

[2] string: input() always returns a string, even if a number is typed (e.g., typing 1 returns "1").

[3] Mismatched data type(s): The keys are integers, but room is a string, so "1" in rooms evaluates to False even though 1 exists.

Why the Other Choices Are Wrong

[1] A. bool and string / B. float and bool: There are no boolean or float values in the dictionary.

[2] A. bool / B. float / C. int: input() does not automatically convert to these types.

[3] A. Invalid syntax: The code is syntactically correct.

[3] Other options: The issue is not logic flow; it's strictly a data type mismatch.

When Other Options Could Be Correct

If the keys were stored as strings (rooms = {"1": 'Foyer', "2": 'Conference Room'}), the code would work without conversion, making [3] "No issue" correct in that scenario.

21
New cards

You find errors while evaluating the following code. Line numbers are included for

reference only.

01 numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

02 index = 0

03 while (index < 10)

04 print(numbers[index])

05

06 if numbers(index) = 6

07 break

08 else :

09 index += 1

You need to correct the code at line 03 and line 06.

How should you correct the code? Use the drop-down menus to select the answer choice

that answers each question based on the information presented in the code segment.

Answer Area

Which code segment should you use at line 03? [1]

Which code segment should you use at line 06? [2]

[1] A. while(index < 10): || B. while[index < 10] || C. while(index < 5): || D. while[index < 5]

[2] A. if numbers[index] == 6 || B. if numbers[index] == 6: || C. if numbers(index) == 6 || D. if numbers(index) == 6:

[1]A. while(index < 10):

[2]B. if numbers[index] == 6:

--------------------------------------------------------------------------

✅ Explanation

Why the Correct Answers Are Right

[1] while(index < 10): In Python, while statements must end with a colon (:).

[2] if numbers[index] == 6:

numbers[index] is the correct way to access a list element (not numbers(index), which is invalid).

The equality operator in Python is ==, not =.

A colon (:) is required at the end of the if statement.

Why the Other Choices Are Wrong

[1] B. while[index < 10]: Brackets are invalid syntax for while.

[1] C & D: Changing 10 to 5 incorrectly limits the loop to half the list.

[2] A. if numbers[index] == 6 (without colon): Missing colon causes a SyntaxError.

[2] C & D: numbers(index) is invalid because lists use square brackets, not parentheses.

When Other Options Could Be Correct

If you wanted to stop at half the list intentionally, C. while(index < 5): would be valid logically, but not for this requirement.

If using a function instead of a list, numbers(index) would make sense, but here numbers is clearly a list.

22
New cards

You are writing a program that calculates a user's year of birth. The program asks users

for their age and the current year, then outputs the user's year of birth. You write the

following code.

Line numbers are included for reference only.

01 age = input("Enter your age: ")

02 year = input("Enter the four digit year: ")

03 born = eval(year) - eval(age)

04 message = "You were born in " + str(born)

05 print(message)

You need to ensure that the program uses the appropriate data types.

What data types are used? Use the drop-down menus to select the answer choice that

answers each question based on the information presented in ¡ne code segment.

Answer Area

What data type is age in line 01? [1]

What data type is born in line 03? [2]

What data type is message in line 04?[3]

[1] A. int B. str C. float

[2] A. int B. str C. float

[3] A. int B. str C. float

[1]B. str

[2]A. int

[3]B. str

--------------------------------------------------------------------------

✅ Explanation

Why the Correct Answers Are Right

[1] B. str - input() always returns a string by default in Python 3.

[2] A. int - eval(year) and eval(age) convert the string inputs into numbers; subtraction of two integers results in an integer.

[3] B. str - "You were born in " is a string, and concatenating with str(born) produces another string.

Why the Other Choices Are Wrong

[1] A. int / C. float - Would only be correct if int() or float() was explicitly used instead of input().

[2] B. str / C. float - Subtraction does not produce a string; float would occur only if one input contained decimals.

[3] A. int / C. float - Message is clearly text, not a number.

When Other Options Could Be Correct

If you replaced eval() with float() and entered a decimal age, born would be a float.

If you cast age and year with int() immediately after input, age would be an int instead of a str.

23
New cards

You write the following code:

a = 'Config'

print(a)

b = a

a += 'config2'

print(a)

print(b)

Use the drop-down menus to select the answer choice that answers each question based

on the information presented in the code segment.

Answer Area

What is displayed after the first print? [1]

What is displayed after the second print? [2]

What is displayed after the third print? [3]

[1] A. Config1 B. Config1Config2 C. Config2

[2] A. Config1 B. Config1Config2 C. Config2

[3] A. Config1 B. Config1Config2 C. Config2

[1]A. Config1

[2]B. Config1Config2

[3]A. Config1

--------------------------------------------------------------------------

✅ Explanation

Why the Correct Answers Are Right

[1] A. Config - The first print simply outputs the initial value of a.

[2] B. Configconfig2 - The += operator concatenates the string "config2" to a, so a becomes "Configconfig2".

[3] A. Config - b was assigned the old value of a before modification; strings are immutable, so b still holds "Config".

Why the Other Choices Are Wrong

"Config1" or "Config1Config2" are incorrect because "Config1" was never assigned to any variable.

"Config2" is wrong because the concatenation does not replace "Config"; it appends to it.

When Other Options Could Be Correct

If you used a = b after modifying a, then the third print would also show "Configconfig2".

24
New cards

You are writing a function that returns the data type of the value that is passed in. You

write the following code. Line numbers are included for reference only.

01 def checkType(value):

02 dataType = type(value)

03 return dataType

04 print(checkType(True))

05 print(checkType(1.0))

06 print(checkType(1))

07 print(checkType("True"))

Use the drop-down menus to select the answer choice that answers each question based

on the information presented in the code segment.

Answer Area

What is printed at line 04? [1]

What is printed at line 05? [2]

What is printed at line 06? [3]

What is printed at line 07? [4]

[1] A. B. C.

[2] A. B. C.

[3] A. B. C.

[4] A. B. C. D.

[1]A. bool

[2]B. float

[3]C. int

[4]D. str

--------------------------------------------------------------------------

✅ Explanation

Why the Correct Answers Are Right

[1] - Passing True returns its type, which is bool.

[2] - Passing 1.0 returns its type, which is float.

[3] - Passing 1 returns its type, which is int.

[4] - Passing "True" (string, not boolean) returns its type, which is str.

Why the Other Choices Are Wrong

True is not a float or int; it's explicitly a bool.

"True" is enclosed in quotes, making it a string, not a bool.

25
New cards

You need to write code that generates a random float with a minimum value of 0.0 and a

maximum value of 1.0.

Which statement should you use?

Answer Area

A. random.randrange()

B. random.randrange(0.0, 1.0)

C. random.random()

D. random.randint(0, 1)

C. random.random()

--------------------------------------------------------------------------

✅ Why C is Correct

Requirement Breakdown:

Need a random float between 0.0 and 1.0.

Must be inclusive of 0.0 and exclusive of 1.0 (Python standard behavior).

Syntax Explanation:

random.random() → Returns a float in the range [0.0, 1.0) directly without extra parameters.

Example:

import random print(random.random()) → 0.572819572 # Example random float between 0.0 and 1.0

❌ Why the Other Options Are Incorrect

A. random.randrange()

Only returns integers; does not support floats.

B. random.randrange(0.0, 1.0)

Invalid because randrange() does not accept floats as arguments.

D. random.randint(0, 1)

Returns only integers (0 or 1), not continuous random floats.

🔄 When the Other Choices Could Be Correct

A → If you need a random integer in a range, e.g., random.randrange(1, 10).B → Would work only if both arguments were integers, e.g., random.randrange(1, 5).D → If you just need a random binary value (0 or 1).

26
New cards

You write a function that reads a data file and prints each line of the file.

You write the following code. Line numbers are included for reference only.

01 def read_file(file):

02 line = None

03 if os.path.isfile(file):

04

data = open(file,'r')

05

06

for line in data:

print(line)

When you run the program, you receive an error on line 03.

What is causing the error?

Answer Area

A. The path method does not exist in the os object.

B. The isfile method does not exist in the path object.

C. You need to import the os library.

D. The isfile method does not accept one parameter.

C. You need to import the os library.

--------------------------------------------------------------------------

✅ Why C is Correct

Requirement Breakdown:

The program uses the os module to check if the file exists.

Python modules must be imported before they can be used.

Root Cause:

The error occurs because the os module was not imported.

Expected Fix:

Import the os module at the start of the program before calling os.path.isfile.

❌ Why the Other Options Are Incorrect

A. The path method does not exist in the os object

Incorrect because os.path is a standard and valid attribute of the os module.

B. The isfile method does not exist in the path object

Incorrect because os.path.isfile is a valid and commonly used method to check file existence.

D. The isfile method does not accept one parameter

Incorrect because isfile accepts exactly one argument, which is the file path.

🔄 When the Other Choices Could Be Correct

A → Could be correct only if there was a typo like writing os.paths instead of os.path.

B → Could be correct only in a rare custom environment where the standard library was altered.

D → Never correct; isfile always requires exactly one parameter in standard Python.

27
New cards

You develop a Python application for your company.

A list named employees contains 200 employee names, the last five being company

management. You need to slice the list to display all employees excluding management.

Which two code segments should you use? Each correct answer presents a complete

solution. Choose two.

Answer Area

A. employees[0:-4]

B. employees [1:-5]

C. employees [:-5]

D. employees [0:-5]

E. employees [1:-4]

C. employees [:-5]

D. employees [0:-5]

--------------------------------------------------------------------------

✅ Why C and D Are Correct

C. employees[:-5]

Default start = 0, so it begins at the first employee.

Stop = -5 means it stops before the last five elements.

✅ Returns all employees except the last five (management).

D. employees[0:-5]

Explicitly starts at index 0 (same as default).

Stop = -5 → same behavior as [:-5].

✅ Also returns all employees except the last five.

❌ Why the Other Options Are Incorrect

A. employees[0:-4]

Stops before the last four elements, leaving one manager still included.

❌ Wrong count.

B. employees[1:-5]

Starts at index 1, so the first employee is skipped.

❌ Excludes one regular employee incorrectly.

E. employees[1:-4]

Skips the first employee and leaves one manager included.

❌ Two mistakes.

28
New cards

Adventure Works Cycles is creating a program that allows customers to log the number of miles biked. The program will send messages based on how many miles the customer logs.

You create the following Python code. Line numbers are included for reference only.

01

02 name = input("What is your name? ")

03 return name

04

05 calories = miles * calories_per_mile

07 return calories

08 distance = int(input("How many miles did you bike this week? "))

09 burn_rate = 50

10 biker = get_name()

11 calories_burned = calc_calories(distance, burn_rate)

12 print(biker, ", you burned about" ,calories_burned, "calories.")

You need to define the two required functions.

Which code segments should you use for line 01 and line 04?

Each correct answer

presents part of the solution. Choose two.

A. 01 def get_name(): B. 01 def get_name(biker): D. 04 def calc_calories(): F. 04 def calc_calories(miles, calories_per_mile):

A. 01 def get_name():

F. 04 def calc_calories(miles, calories_per_mile):

--------------------------------------------------------------------------

✅ Why A and F Are Correct

A. def get_name():

Requirement Breakdown:

The function get_name() is called without any arguments (biker = get_name() line 10).

Therefore, it must be defined with no parameters.

Flow:

Asks for the user's name, then returns it.

F. def calc_calories(miles, calories_per_mile):

Requirement Breakdown:

The function calc_calories is called with two arguments (distance and burn_rate on line 11).

It must therefore accept two parameters.

Flow:

Multiplies miles biked by calories burned per mile, then returns the result.

❌ Why the Other Options Are Incorrect

B. def get_name(biker):

Incorrect because get_name() is called without arguments, which would cause an error if a parameter was required.

D. def calc_calories():

Incorrect because calc_calories() is called with two arguments, so it must accept two parameters.

🔄 When the Other Choices Could Be Correct

B → Could be correct only if you wanted to pass the name as an argument instead of asking for it inside the function (e.g., get_name("John")).

D → Could be correct only if miles and calories_per_mile were global variables instead of being passed as arguments.

29
New cards

You are writing code that generates a random integer with a minimum value of 5 and a

maximum value of 11.

Which two functions should you use? Each correct answer presents a complete solution.

Choose two.

Answer Area

A. random.randint(5, 11)

B. random.randrange(5, 12, 1)

C. random.randint(5, 12)

D. random.randrange(5, 11, 1)

A. random.randint(5, 11)

B. random.randrange(5, 12, 1)

--------------------------------------------------------------------------

✅ Why A is Correct

random.randint(5, 11)

Behavior: Returns an integer inclusive of both endpoints.

Range: 5, 6, 7, 8, 9, 10, 11.

Matches requirement exactly.

✅ Why B is Correct (Even with 12)

random.randrange(5, 12, 1)

Behavior: Returns integers from start up to but NOT including stop.

Range with stop=12: 5, 6, 7, 8, 9, 10, 11.

Why 12? Because to include 11, we must set stop to one more than the max value.

So even though 12 appears in the code, it's never returned. It's just the exclusive boundary.

❌ Why D is Wrong

random.randrange(5, 11, 1)

Range: 5, 6, 7, 8, 9, 10 (11 is excluded because stop=11).

Fails requirement (max value 11 must be possible).

❌ Why C is Wrong

random.randint(5, 12)

Range: 5 to 12 inclusive.

Fails requirement because it allows 12.

30
New cards

You are creating a function that manipulates a number. The function has the following

requirements:

. A float is passed into the function

. The function must take the absolute value of the float

. Any decimal points after the integer must be removed

Which two math functions should you use? Each correct answer is part of the solution.

Choose two.

Answer Area

A. math.ceil(x)

B. math.fmod(x)

C. math.floor(x)

D. math.frexp(x)

E. math.fabs(x)

C. math.floor(x)

E. math.fabs(x)

--------------------------------------------------------------------------

✅ Why C and E Are Correct

C. math.floor(x)

Requirement Breakdown:

Removes all decimal points after the integer by rounding down to the nearest whole number.

Works correctly after taking the absolute value.

Example:

math.floor(7.9) → 7

math.floor(-7.9) → -8 (but will be used after fabs to ensure positivity).

E. math.fabs(x)

Requirement Breakdown:

Returns the absolute value of a float.

Converts negative floats to positive without changing the type.

Example:

math.fabs(-7.9) → 7.9

❌ Why the Other Options Are Incorrect

A. math.ceil(x)

Rounds up to the nearest whole number, which does not meet the requirement of simply removing decimals.

B. math.fmod(x)

Returns the remainder of division, not useful for removing decimals or taking absolute values.

D. math.frexp(x)

Breaks a float into its mantissa and exponent, unrelated to the requirement.

🔄 When the Other Choices Could Be Correct

A → If you needed to always round up instead of truncating decimals.

B → If you were calculating a remainder in a division operation.

D → If you needed to analyze binary floating-point representation.

31
New cards

Woodgrove Bank must generate a report that shows the average balance for all

customers each day. The report must truncate the decimal portion of the balance.

Which two code segments should you use? Each correct answer presents a complete

solution. Choose two.

Answer Area

A. average_balance = total_deposits**number_of_customers

B. average_balance = total_deposits//number_of_customers

C. average_balance = int(total_deposits/number_of_customers)

D. average_balance = float(total_deposits//number_of_customers)

B. average_balance = total_deposits//number_of_customers

C. average_balance = int(total_deposits/number_of_customers)

--------------------------------------------------------------------------

✅ Why B and C Are Correct

B. average_balance = total_deposits // number_of_customers

// (floor division) automatically discards the decimal portion.

If total_deposits = 1050 and number_of_customers = 100,

→ 1050 // 100 = 10 (truncated, not rounded).

✅ Meets the requirement to truncate decimals.

C. average_balance = int(total_deposits / number_of_customers)

/ performs normal division, then int() explicitly truncates the decimal part.

If 1050 / 100 = 10.5,

→ int(10.5) = 10.

✅ Also meets the truncation requirement.

❌ Why the Other Options Are Incorrect

A. average_balance = total_deposits ** number_of_customers

** is the exponentiation operator, not division.

Completely unrelated to averaging.

D. average_balance = float(total_deposits // number_of_customers)

// truncates correctly, but casting to float contradicts the requirement to report a truncated integer average.

Would output 10.0 instead of 10.

32
New cards

You work on a team that is developing a game for AdventureWorks.

You need to write code that generates a random number that meets the following

requirements:

. 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 answer presents a

complete solution. Choose two.

Answer Area

A. from random import randrange

print(randrange(5, 100, 5))

B. from random import randint

print(randint(1, 20) * 5)

C. from random import randint

print(randint(0, 20) * 5)

D. from random import randrange

print(randrange(0, 100, 5))

A. from random import randrange print(randrange(5, 100, 5))

B. from random import randint print(randint(1, 20) * 5)

--------------------------------------------------------------------------

✅ Why A and B Are Correct

A. randrange(5, 100, 5)

Requirement Breakdown:

Start at 5 → ensures the lowest possible number is 5.

Stop at 100 → highest possible generated number is 95 (since randrange excludes the stop value, but 100 is not required as per Python's half-open range behavior).

Step of 5 → guarantees every generated number is a multiple of 5.

Example Output: 5, 10, 15, ..., 95

B. randint(1, 20) * 5

Requirement Breakdown:

Generates an integer between 1 and 20 (inclusive).

Multiplying by 5 → results in multiples of 5 from 5 to 100.

Example Output: 5, 10, 15, ..., 100

❌ Why the Other Options Are Incorrect

C. randint(0, 20) * 5

Can generate 0, which violates the requirement (minimum must be 5).

D. randrange(0, 100, 5)

Can generate 0, violating the minimum requirement.

Maximum possible output is 95, but the issue is mainly with the 0.

🔄 When the Other Choices Could Be Correct

C → If 0 was allowed as a valid multiple of 5.

D → If 0 was an acceptable lower bound for the game logic.

33
New cards

You are creating a function that reads a data file and prints each line of the file.

You write the following code. Line numbers are included for reference only.

01 import os

02 def read_file(file):

03 line = None

04 if os.path.isfile(file):

05 data = open(file,'r')

06 while line != '':

07 line = data.readline()

08 print(line)

The code attempts to read the file even if the file does not exist.

You need to correct the code.

Which three lines have indentation problems? Each correct answer presents part of the

solution. Choose three.

Answer Area

A. Line 01

B. Line 02

C. Line 03

D. Line 04

E. Line 05

F. Line 06

G. Line 07

H. Line 08

F. Line 06

G. Line 07

H. Line 08

--------------------------------------------------------------------------

✅ Why F, G, and H Are Correct

F. Line 06 (while line != '' should be indented under the if statement)

Requirement Breakdown:

The while loop must only run if the file exists (os.path.isfile(file) == True).

As written, it is at the same indentation level as the if, causing it to execute even if the condition fails.

G. Line 07 (line = data.readline() should be indented under the while loop)

Requirement Breakdown:

File reading should occur inside the loop.

Misaligned indentation makes it execute outside the intended loop iteration.

H. Line 08 (print(line) should be indented under the while loop)

Requirement Breakdown:

The print statement must run during each loop iteration, not after the loop completes.

Incorrect indentation causes it to execute after the loop ends, defeating the purpose.

❌ Why the Other Options Are Incorrect

A (Line 01) → Correct global import, no indentation issue.

B (Line 02) → Properly defines the function at the top level.

C (Line 03) → Correctly indented inside the function body.

D (Line 04) → Properly aligned under the function body as part of the if statement.

E (Line 05) → Correctly indented under the if block.

🔄 When the Other Choices Could Be Correct

A, B → Only incorrect if placed inside another function or class block, which is not the case here.

C, D, E → Would only be problematic if nested incorrectly (e.g., if open() was outside the if block or function scope).

34
New cards

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 lines of code to accept input

item = input("Enter the item name: ")

sales = input("Enter the quantity: ")

The output must meet the following requirements:

. Strings must be enclosed inside of double-quotes

. Numbers must not be enclosed in quotes or other characters

. Each item must be separated with a comma

You need to complete the code to meet the requirements.

Which three code segments should you use? Each correct answer presents a complete

solution. Choose three.

Answer Area

A. print('"{0}",{1}'.format(item, sales))

B. print(item + ',' + sales)

C. print('"' + item + '",' + sales)

D. print("{0},{1}".format(item, sales))

E. print('"%s", %s' % (item, sales))

A. print('"{0}",{1}'.format(item, sales))

C. print('"' + item + '",' + sales)

E. print('"%s", %s' % (item, sales))

--------------------------------------------------------------------------

✅ Why A, C, and E Are Correct

A. print('"{0}",{1}'.format(item, sales))

Requirement Breakdown:

"{0}" → Encloses the item (string) in double quotes.

{1} → Prints sales (numeric input) without quotes.

Comma separation is correctly handled by the format string.

C. print('"' + item + '",' + sales)

Requirement Breakdown:

'\"' + item + '\"' → Manually concatenates double quotes around the item.

',' + sales → Adds a comma before sales without enclosing it in quotes.

E. print('"%s", %s' % (item, sales))

Requirement Breakdown:

"%s" → Properly encloses item in double quotes.

%s → Prints sales as-is, without quotes.

Comma separation is handled in the format string.

❌ Why the Other Options Are Incorrect

B. print(item + ',' + sales) → Fails to enclose the string (item) in double quotes.

D. print("{0},{1}".format(item, sales)) → Prints the string without double quotes around item.

🔄 When the Other Choices Could Be Correct

B → Only valid if no quotes were required around the string.

D → Acceptable if the requirement was plain comma-separated values without enforced quoting.

35
New cards

You are building a Python program that displays all of the prime numbers from 2 to 100.

How should you complete the code? To answer, drag the appropriate code segments to

the correct location. Each code segment may be used once, more than once, or not at all.

You may need to drag the split bar between panes or scroll to view content.

NOTE: Each correct selection is worth one point.

Code Segments

[A] p=2

while p <= 100:

is_prime = True

[B] p=2

is_prime = True

while p <= 100:

[C] break

[D] continue

[E] p = p + 1

[F] for i in range(2, p):

if p / i == 0:

is_prime = False

[G] for i in range(2, p):

if p % i == 0:

is_prime = False

Answer Area

[1] __________

[2] __________

[3] __________

if is_prime == True:

print(p)

[4] __________

[A] p=2 while p <= 100: is_prime = True

[G] for i in range(2, p): if p % i == 0: is_prime = False

[C] break

[E] p = p + 1

--------------------------------------------------------------------------

✅ Why A, G, C, and E Are Correct

[1] A → p=2 while p <= 100: is_prime = True

Requirement Breakdown:

Starts from the first prime number 2.

Loops until 100 (inclusive).

Initializes is_prime to True for every new value of p.

[2] G → for i in range(2, p): if p % i == 0: is_prime = False

Requirement Breakdown:

Checks divisibility of p by any number from 2 to p-1.

% (modulus) ensures correct prime checking (not /, which would incorrectly check division results).

Sets is_prime to False if a divisor exists.

[3] C → break

Requirement Breakdown:

Exits the for loop early when a divisor is found.

Optimizes performance by skipping unnecessary checks once non-prime status is determined.

[4] E → p = p + 1

Requirement Breakdown:

Increments p after evaluating whether it is prime.

Ensures all numbers from 2 to 100 are evaluated sequentially.

❌ Why the Other Options Are Incorrect

B → Misplaced initialization (is_prime should reset inside the loop, not before it).

D (continue) → Skips remaining checks unnecessarily; prime determination requires breaking, not continuing.

F (p / i == 0) → Incorrect operator; / checks division, not modulus.

🔄 When the Other Choices Could Be Correct

B → Could work only if restructured with proper indentation, but redundant for this problem.

D → Useful if skipping to the next iteration after marking is_prime = False, but less efficient than breaking immediately.

F → Not valid for prime logic; division equality rarely used for this purpose.

36
New cards

You are developing a Python application for your company.

You write the following code:

numList = [1,2,3,4,5]

alphaList = ["a","b","c","d","e"]

print(numList is alphaList)

print(numList == alphaList)

numList = alphaList

print(numList is alphaList)

print(numList == alphaList)

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

select No.

Answer Area Yes No

[1] What is displayed after the first print? 〇 〇

[2] What is displayed after the second print? 〇 〇

[3] What is displayed after the third print? 〇 〇

[4] What is displayed after the fourth print? 〇 〇

[1] NO

[2] NO

[3] YES

[4] YES

--------------------------------------------------------------------------

✅ Why [1] NO, [2] NO, [3] YES, [4] YES Are Correct

Code Behavior Analysis

Initial Lists:

numList = [1,2,3,4,5]

alphaList = ["a","b","c","d","e"]

[1] First Print → print(numList is alphaList) → False → ✅ NO

is checks object identity (same memory reference).

numList and alphaList are two separate list objects in memory.

False is displayed, so the correct choice is NO.

[2] Second Print → print(numList == alphaList) → False → ✅ NO

== checks value equality.

[1,2,3,4,5] ≠ ["a","b","c","d","e"].

False is displayed, confirming NO.

Assignment: numList = alphaList

Now numList and alphaList point to the same list object.

[3] Third Print → print(numList is alphaList) → True → ✅ YES

Both variables reference the same memory object after the assignment.

True is displayed.

[4] Fourth Print → print(numList == alphaList) → True → ✅ YES

Both now reference the same list, so their values are identical.

True is displayed.

❌ Why the Other Options Are Incorrect

Any "YES" for [1] or [2] would incorrectly assume the lists were the same object or had identical values initially.

🔄 When the Other Choices Could Be Correct

[1] YES → Only if both lists were set to reference the same object at creation (e.g., numList = alphaList immediately).

[2] YES → Only if both lists had the same values at initialization.

37
New cards

During school holidays, you volunteer to explain some basic programming concepts to your younger siblings. You want to introduce the concept of data types in Python. You create the following three code segments:

* Code segment 1

x1 = "20"

y1 = 3

a = x1 * y1

* Code segment 2

x2 = 6

y2 = 4

b = x2 / y2

* Code segment 3

x3 = 2.5

y3 = 1

c = x3 / y3

Answer Area Yes No

[1] After executing code segment 1, the data type of variable a is str. 〇 〇

[2] After executing code segment 2, the data type of variable b is float. 〇 〇

[3] After executing code segment 3, the data type of variable c is int. 〇 〇

[1] YES

[2] YES

[3] NO

--------------------------------------------------------------------------

✅ Why [1] YES, [2] YES, [3] NO Are Correct

Code Behavior Analysis

[1] Code Segment 1 → a = x1 * y1 → a is str → ✅ YES

Requirement Breakdown:

x1 = "20" (string)

y1 = 3 (integer)

In Python, "string" integer repeats the string → "20" 3 = "202020"

Therefore, a is of type str.

[2] Code Segment 2 → b = x2 / y2 → b is float → ✅ YES

Requirement Breakdown:

x2 = 6 (int), y2 = 4 (int)

/ always returns a float in Python, even for integer division.

6 / 4 = 1.5 → b is of type float.

[3] Code Segment 3 → c = x3 / y3 → c is NOT int → ✅ NO

Requirement Breakdown:

x3 = 2.5 (float), y3 = 1 (int)

/ returns a float → 2.5 / 1 = 2.5

Therefore, c is of type float, not int.

❌ Why the Other Options Are Incorrect

[1] NO → Wrong because string multiplication by an integer always yields a string.

[2] NO → Wrong because / never returns an integer, even with two integers.

[3] YES → Wrong because 2.5 / 1 is a float, not an int.

🔄 When the Other Choices Could Be Correct

[1] NO → Would be correct only if x1 were a number (e.g., 20 * 3 = 60).

[2] NO → Would be correct if you used // (floor division), e.g., 6 // 4 = 1 (int).

[3] YES → Would be correct if both operands were integers and used //, e.g., 4 // 2 = 2 (int).

38
New cards

You create a function to calculate the power of a number by using Python. You need to ensure that the function ¡s documented with comments. You create the following code. Line numbers are included for reference only.

01 # The calc_power function calculates exponents

02 # x is the base

03 # y is the exponent

04 # The value of x raised to the y power is returned

05 def calc_power(x, y):

06 comment = "#Return the value"

07 return x**y 4 raise x to the y power

Answer Area Yes No

[1] Lines 01 through 04 will be ignored for syntax checking. 〇 〇

[2]The pound sign (#) is optional for lines 02 and 03. 〇 〇

[3]The pound sign (#) is optional for lines 02 and 03. 〇 〇

[4] Line 07 contains an inline comment. 〇 〇

[1] YES

[2] NO

[3] NO

[4] NO

--------------------------------------------------------------------------

✅ Why [1] YES, [2] NO, [3] NO, [4] YES Are Correct

Code Behavior Analysis

[1] Lines 01 through 04 will be ignored for syntax checking → ✅ YES

Any line starting with # in Python is a comment and ignored by the interpreter during execution and syntax checking.

[2] The pound sign (#) is optional for lines 02 and 03 → ❌ NO

Comments in Python must start with #.

Without #, Python will treat the line as executable code, causing a syntax error.

[3] The pound sign (#) is optional for lines 02 and 03 → ❌ NO

Same reasoning as [2]; the pound sign is mandatory for comments.

[4] Line 07 contains an inline comment → ❌ NO

The code is:

return x**y 4 raise x to the y power

There's no #, so this is invalid syntax, not a comment.

A valid inline comment would be:

return x**y # raise x to the y power

❌ Why the Other Options Are Incorrect

[4] YES → Incorrect because no actual inline comment exists; Python reads 4 as code, not a comment.

39
New cards

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

select No.

Answer Area Yes No

[1] A try statement can have one or more except clauses. 〇 〇

[2] A try statement can have a finally clause without an except clause. 〇 〇

[3] A try statement can have a finally clause and an except clause.

〇 〇

[4] A try statement can have one or more finally clauses. 〇 〇

[1] YES

[2] YES

[3] YES

[4] NO

--------------------------------------------------------------------------

✅ Why [1] YES, [2] YES, [3] YES, [4] NO Are Correct

[1] A try statement can have one or more except clauses → ✅ YES

Python allows handling multiple types of exceptions separately by attaching multiple except clauses to a single try block.

[2] A try statement can have a finally clause without an except clause → ✅ YES

A finally block can be used solely to ensure that cleanup or final actions occur, even if no exception handling (except) is provided.

[3] A try statement can have a finally clause and an except clause → ✅ YES

A single try statement can include both except for error handling and finally for guaranteed cleanup after execution.

[4] A try statement can have one or more finally clauses → ❌ NO

Python permits only one finally block per try statement. Multiple finally clauses are not allowed.

❌ Why the Other Options Are Incorrect

[4] YES → Incorrect because Python does not support more than one finally clause.

🔄 When the Other Choices Could Be Correct

[4] YES → Would only apply in languages that hypothetically allow multiple finalization stages, which Python does not.

40
New cards

The function has the following requirements:

. If no value is specified for points, then points start at one

. If bonus is True, then points must be doubled

You write the following code. Line numbers are included for reference only.

01 def increment_score(score, bonus, points):

02 if bonus == True:

03 points = points * 2

04 score = score + points

05 return score

06 points = 5

07 score = 10

08 new_score = increment_score(score, True, points)

Answer Area

[1] To meet the requirements, line 01 must be changed to the following: def increnient_score(score, bonus, points = 1): 〇 〇

[2] Once any parameter is defined with a default value, any parameters to the right must also be defined with default values. 〇 〇

[3] If the function is called with only two parameters, the value of the third parameter will be None. 〇 〇

[4] Line 03 will also modify the value of the variable points declared at line 06. 〇 〇

[1] YES

[2] YES

[3] NO

[4] NO

--------------------------------------------------------------------------

✅ Why [1] YES, [2] YES, [3] NO, [4] NO Are Correct

[1] To meet the requirements, line 01 must be changed to: def increment_score(score, bonus, points = 1) → ✅ YES

The requirement specifies that if no value is provided for points, it should default to 1. Setting a default value for points satisfies this requirement.

[2] Once any parameter is defined with a default value, any parameters to the right must also be defined with default values → ✅ YES

Python syntax enforces that parameters with default values must come after all parameters without default values.

[3] If the function is called with only two parameters, the value of the third parameter will be None → ❌ NO

Because points is explicitly given a default value (1), calling the function with two parameters assigns points = 1, not None.

[4] Line 03 will also modify the value of the variable points declared at line 06 → ❌ NO

Variables inside a function have local scope unless explicitly declared as global. Modifying points inside the function does not affect the points variable outside.

❌ Why the Other Options Are Incorrect

[3] YES → Incorrect because points will never be None if a default value is set.

[4] YES → Incorrect because local and global variables are separate unless declared as global.

🔄 When the Other Choices Could Be Correct

[3] YES → Only if no default value is assigned to points and the function is explicitly called without passing it, which is not the case here.

[4] YES → Would only occur if points was declared as a global variable or passed as a mutable object that is modified inside the function.

41
New cards

You are creating a Python program that compares numbers.

You create the following code. Line numbers are included for reference only.

01 num1 = eval(input ("Please enter the first number: "))

02 num2 = eval(input ("Please enter the second number: "))

03 if num1 == num2:

04 print("The two numbers are equal.")

05 if num1 <= num2:

06 print("Number 1 is less than number 2.")

07 if num1 > num2:

08 print("Number 1 is greater than number 2.")

09 if num2 = num1:

10 print("The two numbers are the same.")

You need to ensure that the comparisons are accurate.

Answer Area

[1] The print statement at line 04 will only print if the two numbers are equal in value. 〇 〇

[2] The print statement at line 06 will only print if num1 is less than num2. 〇 〇

[3] The print statement at line 08 will only print if num1 is greater than num2. 〇 〇

[4] The statement at line 09 is an invalid comparison. 〇 〇

[1] YES

[2] NO

[3] YES

[4] YES

--------------------------------------------------------------------------

✅ Why [1] YES, [2] NO, [3] YES, [4] YES Are Correct

[1] The print statement at line 04 will only print if the two numbers are equal in value → ✅ YES

The condition if num1 == num2: correctly compares equality, so it only prints when both numbers are equal.

[2] The print statement at line 06 will only print if num1 is less than num2 → ❌ NO

The condition if num1 <= num2: also evaluates to true when the numbers are equal, so it is not limited to strictly less-than comparisons.

[3] The print statement at line 08 will only print if num1 is greater than num2 → ✅ YES

The condition if num1 > num2: correctly ensures it only prints when num1 is greater than num2.

[4] The statement at line 09 is an invalid comparison → ✅ YES

The code uses = instead of ==, which is assignment, not comparison. This causes a syntax error in Python.

❌ Why the Other Options Are Incorrect

[2] YES → Incorrect because <= includes equality, which violates the "only if less than" statement.

🔄 When the Other Choices Could Be Correct

[2] YES → Would be correct only if the condition were explicitly if num1 < num2: instead of <=.

42
New cards

You are creating a Python script to evaluate input and check for upper and lower case.

Which four code segments should you use to develop the solution? To answer, move the

appropriate code segment from the list of code segments to the answer area and arrange

them in the correct order.

Code Segments

[A] else:

print(name, "is upper case.")

[B] else:

print(name, "is mixed case.")

[C] else:

print(name, "is lower case.")

[D] if name.lower() == name:

print(name. "is all lower case.")

[E] elif name.upper() == name:

print(name, "is all upper case.")

[F] name = input("Enter your name: ")

Answer Area

[F] name = input("Enter your name: ")

[D] if name.lower() == name:

print(name. "is all lower case.")

[E] elif name.upper() == name:

print(name, "is all upper case.")

[B] else:

print(name, "is mixed case.")

✅ Why F, D, E, and B Are Correct (in that order)

1) F → name = input("Enter your name: ")

The script must first take user input before any evaluation.

✅ This initializes the variable name.

2) D → if name.lower() == name:

if name.lower() == name:

print(name, "is all lower case.")

Checks if all letters are lowercase by comparing the string to its .lower() version.

✅ If they match, the entire string is lowercase.

3) E → elif name.upper() == name:

elif name.upper() == name:

print(name, "is all upper case.")

Checks if all letters are uppercase by comparing the string to its .upper() version.

✅ If they match, the entire string is uppercase.

4) B → else:

else:

print(name, "is mixed case.")

If neither condition above is true, the string must be mixed case.

✅ Covers the default scenario.

✅ Final Ordered Script

name = input("Enter your name: ")

if name.lower() == name:

print(name, "is all lower case.")

elif name.upper() == name:

print(name, "is all upper case.")

else:

print(name, "is mixed case.")

❌ Why A and C Are Incorrect

A (else: print(name, "is upper case.")) → Redundant because E already handles uppercase.

C (else: print(name, "is lower case.")) → Incorrect logic; if it reached else, it's mixed, not lower.

43
New cards

Tailspin Toys is converting an existing application to Python. You are creating

documentation that will be used by several interns who are working on the team.

You need to ensure that arithmetic expressions are coded correctly.

What is the correct order of operations for the six classes of operations ordered from

first to last in order of precedence? To answer, move all operations from the list of

operations to the answer area and arrange them in the correct order.

Operations

[A] And

[B] Addition and Subtraction

[C] Multiplication and Division

[D] Exponents

[E] Parenthesis

[F] Unary positive, negative, not

[E] Parenthesis

[D] Exponents

[F] Unary positive, negative, not

[C] Multiplication and Division

[B] Addition and Subtraction

[A] And

--------------------------------------------------------------------------

✅ Why E, D, F, C, B, and A Are Correct (in that order)

The question asks for Python's operator precedence from highest to lowest. Here's the breakdown:

1) E → Parentheses (())

✅ Highest precedence: Expressions inside parentheses are always evaluated first.

Example:

result = (2 + 3) 4 # 2+3 evaluated first → 54=20

2) D → Exponents (**)

✅ Next highest precedence.

Example:

result = 2 + 3 * 2 # 3*2=9 first → 2+9=11

3) F → Unary positive (+), negative (-), and not

✅ Unary operations are applied before standard arithmetic.

Example:

result = -3 * 2 # Equivalent to -(3*2)= -9

4) C → Multiplication and Division (*, /, //, %)

✅ Multiplicative operators have higher precedence than addition or subtraction.

Example:

result = 2 + 3 4 # 34=12 first → 2+12=14

5) B → Addition and Subtraction (+, -)

✅ Evaluated after multiplication/division.

Example:

result = 10 - 2 + 3

6) A → And (and)

✅ Logical and is one of the lowest-precedence operators, evaluated last.

Example:

result = 3 + 2 and 4 # 3+2 first → 5 and 4 → True (4)

44
New cards

You are writing a function that works with files.

You need to ensure that the function returns None if the file does not exist. If the file

does exist, the function must return the first line.

You write the following code:

import os

def get_first_line(filename, mode):

In which order should you arrange the code segments to complete the function? To

answer, move all code segments from the list of code segments to the answer area and

arrange them in the correct order.

Code Segments

[A] return file. readline()

[B] else:

[C] if os.path.isfile(filename):

[D] with open (filename, 'r') as file:

[E] return None

Answer Area

[1] [C] if os.path.isfile(filename):

[2] [D] with open (filename, 'r') as file:

[3] [A] return file. readline()

[4] [B] else:

[5] [E] return None

--------------------------------------------------------------------------

✅ Why [1] C, [2] D, [3] A, [4] B, [5] E Are Correct

[1] if os.path.isfile(filename): → ✅ C

Checks if the file exists before proceeding. This is required to meet the condition of returning None when the file does not exist.

[2] with open(filename, 'r') as file: → ✅ D

Opens the file safely in read mode if it exists. Using a context manager (with) ensures proper resource handling.

[3] return file.readline() → ✅ A

Reads and returns the first line of the file as required.

[4] else: → ✅ B

Defines the alternative path if the file does not exist.

[5] return None → ✅ E

Ensures that None is returned when the file is not found, satisfying the requirement.

❌ Why Any Other Order Is Incorrect

Placing E before C would return None prematurely, without checking if the file exists.

Placing A before D would cause an error because the file would not be opened yet.

🔄 Alternative Correct Implementation

The order remains fixed because Python requires if → with → return in this sequence to meet the functional requirements.

45
New cards

You are writing a function ¡n Python that must meet the following requirements:

. The function accepts a list and a string as parameters.

. The function must search for the string in the list,

. If the string is found in the list, the function must print a message indicating that the

string was found and then stop iterating through the list.

. If the string is not found, the function must print a message indicating that the string

was not found in the list.

In which order should you arrange the code segments to develop the solution? To

answer, move all code segments from the list of code segments to the answer area and

arrange them in the correct order.

Code Segments

[A] for i in range(len(items)):

[B] else:

print("{0} as not found in the list.".format(term))

[C] if items[i] == term:

print("{0} was found in the list.".format(term))

[D] break

[E] def search(items, term):

[1] [E] def search(items, term):

[2] [A] for i in range(len(items)):

[3] [C] if items[i] == term: print("{0} was found in the list.".format(term))

[4] [D] break

[5] [B] else: print("{0} as not found in the list.".format(term))

--------------------------------------------------------------------------

✅ Why [1] E, [2] A, [3] C, [4] D, [5] B Are Correct

[1] def search(items, term): → ✅ E

Defines the function with the required parameters: a list (items) and a string (term).

[2] for i in range(len(items)): → ✅ A

Iterates through the list by index to compare each element with the search term.

[3] if items[i] == term: → ✅ C

Checks if the current list element matches the search term. If true, it prints that the term was found.

[4] break → ✅ D

Stops the iteration immediately after finding the term, as required.

[5] else: print("{0} as not found in the list.".format(term)) → ✅ B

The else in a for loop executes only if the loop completes without encountering a break, correctly handling the "not found" condition.

❌ Why Any Other Order Is Incorrect

Placing B before the loop would incorrectly print "not found" even if the term exists.

Omitting D would continue iterating even after finding the term, violating requirements.

Swapping C and A would attempt to check an undefined index.

🔄 Alternative Correct Implementation

This order is fixed because Python's for...else logic is explicitly designed for search operations where the else executes only if no break is triggered.

46
New cards

You are writing a Python program that evaluates an arithmetic formula.

The formula is described as b equals a multiplied by negative one, then raised to the

second power, where a is the value that will be input and b is the result

You create the following code segment Line numbers are included for reference only.

01 a = eval(input("Enter a number for the equation: "))

02 b =

You need to ensure that the result is correct.

How should you complete the code on line 02? To answer, drag the appropriate code

segment to the correct location. Each code segment may be used once, more than once,

or not at all. You may need to drag the split bar between panes or scroll to view content.

Code Segments

[A] -

[B] (

[C] )

[D] **

[E] **2

[F] 2

[G] A

Answer Area

[1] [B] (

[2] [A] -

[3] [G] A

[4] [C] )

[5] [E] **2

--------------------------------------------------------------------------

✅ Why [1] B, [2] A, [3] G, [4] C, [5] E Are Correct

The requirements specify the arithmetic operation b = (-a)², which matches Python's operator precedence and syntax:

(-a) → ✅ B, A, G, C

B (() → ✅ Opens the expression to ensure correct precedence.

A (-) → ✅ Negates the input value a.

G (a) → ✅ References the user-provided variable.

C ()) → ✅ Closes the negated expression so that the squaring applies to the entire value.

**2 → ✅ E

E (**2) → ✅ Squares the entire negated value, ensuring the correct mathematical result ((-a) × (-a)).

✅ Completed Line 02

b = (-a)**2

❌ Why the Other Options Are Incorrect

D (*) + F (2) → Would require two separate segments ( and 2), but the provided code expects a single *2 token.

Placing - after squaring (a**2) → Would change the result to negative squared value (-(a²)), which is incorrect.

Repeating G (a) elsewhere → Produces invalid syntax.

47
New cards

You need to print the data so that it looks like the following sample:

Oranges 5.6 1.33

Apples 2.0 0.54

Grapes 10.2 10.96

Specifically, the print out must meet the following requirements:

. The fruit name must print left-aligned in a column 10 spaces wide.

. The weight must print right-aligned in a column 5 spaces wide with up to one digit after

the decimal point.

. The price must print right-aligned in a column 7 spaces wide with up to two digits after the decimal point. You write the following code. Line numbers included are for reference only.

01 def print_table(file):

02 data = open(file,'r')

03 for record in data:

04 fields = record.split(",")

05 ? How should you complete line 05?

Code Segments

[A] print("

[B] {10:0}

[C] {5:1f}

[D] {7:2f}

[E] {2:7.2f}

[F] {1:5.1f}

[G] {0:10}

Answer Area

[1] ____. ".format(fields[0], eval(fields[1]), eval(fields[2])))

[1] [A] print ("

[2] [G] {0:10}

[3] [F] {1:5.1f}

[4] [E] {2:7.2f}

--------------------------------------------------------------------------

✅ Why [1] A, [2] G, [3] F, [4] E Are Correct

The requirements specify strict formatting rules, which match the Python format string syntax:

print(" → ✅ AStarts the print statement and opens the formatted string.

{0:10} → ✅ GPrints the fruit name (fields[0]) left-aligned in a 10-character-wide column. Strings are left-aligned by default.

{1:5.1f} → ✅ FPrints the weight (fields[1]) right-aligned in a 5-character-wide column with 1 digit after the decimal.

{2:7.2f} → ✅ EPrints the price (fields[2]) right-aligned in a 7-character-wide column with 2 digits after the decimal.

✅ Completed Line 05

print("{0:10}{1:5.1f}{2:7.2f}".format(fields[0], eval(fields[1]), eval(fields[2])))

❌ Why the Other Options Are Incorrect

B {10:0} → Invalid syntax; reverses index and width.

C {5:1f} and D {7:2f} → Wrong indexing; they specify width but not proper formatting for positional arguments.

48
New cards

You are writing a Python program to perform arithmetic operations.

You create the following code:

a = 11

b = 4

What is the result of each arithmetic expression? To answer, drag the appropriate

expression from the column on the left to its result on the right. Each expression may be

used once, more than once, or not at all.

Results Answer Area

[A] print(a / b)

[B] print(a // b)

[C] print(a % b)

Answer Area

2 [1] ________________

3 [2] ________________

2.75 [3] ________________

[1] [B] print(a // b)

[2] [C] print(a % b)

[3] [A] print(a / b)

--------------------------------------------------------------------------

✅ Why [1] B, [2] C, [3] A Are Correct

print(a // b) → ✅ B → 2// is floor division, which returns the integer part of the division.11//4=211 // 4 = 211//4=2.

print(a % b) → ✅ C → 3% is the modulus operator, which returns the remainder of the division.1111 % 4 = 311.

print(a / b) → ✅ A → 2.75/ is true division, which returns the floating-point division result.11/4=2.7511 / 4 = 2.7511/4=2.75.

❌ Why Other Options Are Incorrect

print(a / b) cannot produce an integer (2 or 3) since it always returns a float.

print(a // b) never returns a float, so it cannot be 2.75.

print(a % b) only gives the remainder, not the quotient or division result.

49
New cards

Match the data type to the type operations.

To answer, drag the appropriate data type to the correct type operation. Each data type

may be used once, more than once, or not at all.

Data Types

[A] int

[B] float

[C] str

[D] bool

Answer Area

type (+1E10) [1]

type (5.0) [2]

type ("True") [3]

type (False) [4]

[1] [B] float

[2] [B] float

[3] [C] str

[4] [D] bool

--------------------------------------------------------------------------

✅ Why [1] B, [2] B, [3] C, [4] D Are Correct

type(+1E10) → ✅ B → float

1E10 (scientific notation) is always interpreted as a floating-point number in Python.

type(5.0) → ✅ B → float

Any number with a decimal point is a float in Python, even if it represents a whole number.

type("True") → ✅ C → str

Quotation marks indicate a string, regardless of whether the content looks like a boolean value.

type(False) → ✅ D → bool

False is a built-in boolean literal in Python.

❌ Why Other Options Are Incorrect

A (int) is incorrect because none of these expressions evaluate to an integer.

C (str) is only valid for explicitly quoted values.

D (bool) only applies to True or False, not their string equivalents ("True" or "False").

50
New cards

You are writing a Python program. The program collects customer data and stores it in a

database.

The program handles a wide variety of data.

You need to ensure that the program handles the data correctly so that ¡t can be stored in

the database correctly.

Match the data type to the code segment. To answer, drag the appropriate data type

from the column on the left to its code segment on the right. Each data type may be used

once, more than once, or not at all.

Data Types

[A] int

[B] float

[C] str

[D] bool

Answer Area

[1] ____________________. age = 2

[2] ____________________. minor = False

[3] ____________________. name = "contoso"

[4] ____________________. weight = 123.5

[5] ____________________. zip = "81000"

[1] [A] int

[2] [D] bool

[3] [C] str

[4] [B] float

[5] [C] str

--------------------------------------------------------------------------

✅ Why [1] A, [2] D, [3] C, [4] B, [5] C Are Correct

age = 2 → ✅ A → int

Whole numbers without decimals are integers in Python.

minor = False → ✅ D → bool

False is a boolean literal representing a true/false value.

name = "contoso" → ✅ C → str

Any text enclosed in quotes is a string.

weight = 123.5 → ✅ B → float

Numbers with decimal points are floating-point numbers.

zip = "81000" → ✅ C → str

Even though a ZIP code is numeric, it is treated as a string because it is not used for arithmetic operations.

❌ Why Other Options Are Incorrect

A (int) is not valid for ZIP codes because leading zeros or formatting are important in database storage.

B (float) is only for decimal values, not whole numbers stored as text.

D (bool) applies only to True or False, not string equivalents like "True".

51
New cards

You have the following list structure:

alph = "abcdefghijklnnopqrstuvwxyz"

You need to evaluate the result of performing various slicing operations.

Match the result to the slicing operation. To answer, drag the appropriate result from the

column on the left to its slicing operation on the right. Each result may be used once,

more than once, or not at all.

Results

[A] zwtqnkheb

[B] pmjg

[C] defghijklmno

[D] ponmlkjihgfe

[E] defghijklmnop

[F] dgjm

[G] olif

[H] ""

Answer Area

[1] ____________________ . alph[3:15]

[2] ____________________ . alph[3:15:3]

[3] ____________________ . alph[3:15:-3]

[4] ____________________ . alph[15:3:-3]

[5] ____________________ . alph[15:3]

[6] ____________________ . alph[::-3]

[1] [C] defghijklmno

[2] [F] dgjm

[3] [H] ""

[4] [B] pmjg

[5] [H] ""

[6] [A] zwtqnkheb

--------------------------------------------------------------------------

✅ Why [1] C, [2] F, [3] H, [4] B, [5] D, [6] A Are Correct

[1] alph[3:15] → ✅ C → "defghijklmno"

Start = 3 (d), Stop = 15 (p, exclusive).

Extracts indices 3 → 14: d e f g h i j k l n n o.

But careful: The string has duplicate "n", so actual extraction: defghijklnno.

✅ The expected answer given is "defghijklmno" (exam simplification; assuming a correct alphabet without duplicate n).

If we keep the provided sequence as-is, the exact output would be "defghijklnno", but for the exam, follow the given expected answer.

[2] alph[3:15:3] → ✅ F → "dgjm"

Start = 3 (d), Stop = 15, Step = 3.

Extract indices 3, 6, 9, 12:

3:d, 6:g, 9:j, 12:n (but exam says "m", assuming proper alphabet sequence).

Again, due to the typo in alph, real output is "dgj n", but exam expects "dgjm".

[3] alph[3:15:-3] → ✅ H → "" (empty string)

Negative step moves backward, but start(3) is before stop(15).

Python doesn't reverse automatically, so returns empty.

[4] alph[15:3:-3] → ✅ B → "pmjg"

Start = 15 (p), Stop = 3 (exclusive), Step = -3

Extract indices 15, 12, 9, 6: p, n, j, g → "pnjg" (but exam simplifies to "pmjg" assuming correct alphabet order).

[5] alph[15:3] → ✅ H → "" (empty string)

Default step is positive (1), but start(15) > stop(3).

Python reads left-to-right for positive step → empty result.

[6] alph[::-3] → ✅ A → "zwtqnkheb"

[::-3] reverses the string first (...zyx...), then takes every 3rd char.

Correct sequence: "z w t q n k h e b".

⚠ Important Clarification

The provided alph string has a typo (...ijklnnop...).

If we used a correct alphabet ("abcdefghijklmnopqrstuvwxyz"), the expected outputs perfectly match the exam answers.

52
New cards

You are developing a Python program that compares numbers.

You need to ensure that you are using the correct comparison operators.

Evaluate each expression and indicate the correct result. To answer, drag the appropriate

result from the column on the left to its expression on the right. Each result may be used

once, more than once, or not at all.

NOTE: Each correct selection is worth one point.

Results

[A] True

[B] False

[C] 5

[D] None

Answer Area

[1] ____________________ . 0 or 5

[2] ____________________ . bool(0)

[3] ____________________ . None is None

[4] ____________________ . -5 < 0 < 5

[1] [C] 5

[2] [B] False

[3] [A] True

[4] [A] True

--------------------------------------------------------------------------

✅ Why [1] C, [2] B, [3] A, [4] A Are Correct

0 or 5 → ✅ C → 5

or returns the first truthy value. Since 0 is falsy, Python evaluates and returns 5.

bool(0) → ✅ B → False

0 is falsy in Python, so bool(0) evaluates to False.

None is None → ✅ A → True

Identity comparison using is confirms that None is the same singleton object as itself.

-5 < 0 < 5 → ✅ A → True

Chained comparison evaluates both conditions: -5 < 0 and 0 < 5, both of which are True.

❌ Why Other Options Are Incorrect

A (True) for [1] → Incorrect because 0 or 5 does not return a boolean; it returns the first truthy value (5).

C (5) for [2] → Incorrect because bool(0) explicitly converts to a boolean, not a number.

B (False) for [3] → Incorrect because None is None is always True.

B (False) for [4] → Incorrect because -5 < 0 < 5 satisfies both conditions.

53
New cards

The user is allowed up to three guesses.

You write the following code. Line numbers are included for reference only.

01 from random import randint

02 target = randint(1,10)

03 chance = 1

04 print ("Guess an integer from 1 to 10. You will have 3

chances.")

05

06 guess = int(input("Guess an integer: "))

07 if guess > target:

08 print ("Guess is too high")

09 elif guess < target:

10 print ("Guess is too low")

11 else:

12 print ("Guess is just right!")

13

14

The program must allow three guesses. If the user guesses the correct number, the program must stop asking for guesses.

Code Segments

[A] while chance <= 3:

[B] while chance < 3:

[C] break

[D] pass

[E] chance += 1

[F] while chance < 3

[G] chance = 2

Answer Area

Which code segment should you use at line 05? [1]

Which code segment should you use at line 13? [2]

Which code segment should you use at line 14? [3]

[1] [A] while chance <= 3:

[2] [C] break

[3] [E] chance += 1

--------------------------------------------------------------------------

✅ Why [1] A, [2] C, [3] E Are Correct

while chance <= 3: → ✅ A

The program must allow exactly three attempts. Using <= 3 ensures the loop continues as long as the user has not exceeded the three chances.

break → ✅ C

When the user guesses the correct number (else branch), the program should immediately stop asking for more guesses, which is achieved by using break.

chance += 1 → ✅ E

After each incorrect guess, the number of chances used must increase by 1. This keeps track of the attempts correctly.

❌ Why Other Options Are Incorrect

B (while chance < 3:) → Incorrect because this would only allow two attempts (1 and 2), skipping the third.

D (pass) → Incorrect because pass does nothing and does not advance or exit the loop.

F (while chance < 3) → Incorrect because it's missing a colon and would still only allow two attempts.

G (chance = 2) → Incorrect because resetting chance to 2 mid-loop would break the logic of tracking attempts.

🔄 When Other Choices Could Be Correct

B (while chance < 3:) → Could be used if chance started from 0 instead of 1.

D (pass) → Could be used as a placeholder during development but not in production logic.

54
New cards

The program must assign a letter grade as specified in the following table:

Percentage range Letter grade

90 through 100 A

80 through 89 B

70 through 79 C

65 through 69 D

0 through 64 F

For example, if the user enters a 90, the output should be, "Your letter grade is A."

Likewise, if a user enters an 89, the output should be "Your letter grade is B."

Answer Area

#Letter Grade converter

grade = int(input("Enter a numeric grade'))

[1] __ letter_grade = 'A'

[2] __ letter_grade = 'B'

[3] __ letter_grade = 'C'

[4] __ letter_grade = 'D'

else:

letter_grade = 'F'

print("Your letter grade is :", letter_grade)

[1] B. if grade >= 90: C. elif grade > 90: D. elif grade >= 90:

[2] B. if grade >= 80: C. elif grade > 80: D. elif grade >= 80:

[3] A. if grade > 70: B. if grade >= 70: C. elif grade > 70: D. elif grade >= 70:

[4] A. if grade > 65: B. if grade >= 65: C. elif grade > 65: D. elif grade >= 65:

[1] [B] B. if grade >= 90:

[2] [D] D. elif grade >= 80:

[3] [D] D. elif grade >= 70:

[4] [D] D. elif grade >= 65:

--------------------------------------------------------------------------

✅ Why [1] B, [2] D, [3] D, [4] D Are Correct

if grade >= 90: → ✅ B

The highest grade range must be checked first. Using >= 90 ensures that any grade from 90 to 100 is assigned an "A".

elif grade >= 80: → ✅ D

The elif ensures this is only evaluated if the grade is less than 90. The condition >= 80 correctly captures 80-89.

elif grade >= 70: → ✅ D

Similarly, this correctly captures 70-79 after higher ranges are excluded.

elif grade >= 65: → ✅ D

This covers 65-69 after eliminating higher-grade ranges.

The final else defaults to "F" for anything below 65, which is correct.

❌ Why Other Options Are Incorrect

C. elif grade > 90 → Would incorrectly exclude exactly 90 (e.g., 90 would not be an "A").

C. elif grade > 80 → Would incorrectly exclude exactly 80.

A. if grade > 70 / C. elif grade > 70 → Would incorrectly exclude 70.

A. if grade > 65 / C. elif grade > 65 → Would incorrectly exclude 65.

55
New cards

You are writing a Python program to validate employee numbers.

The employee number must have the format ddd-dd-dddd and consist only of numbers

and dashes. The program must print True if the format is correct and print False if the

format is incorrect.

Answer Area

[1] ___________________

parts = ""

[2] ___________________

[3] ___________________

employee_number = input('Enter employee number (ddd-dd-dddd): ")

parts = employee_number. split(' -')

if len(parts) == 3:

if len(parts[0]) == 3 and len(parts[1]) == 2 and len(parts[2]) == 4:

if parts[0].isdigit() and parts[1].isdigit() and

parts[2].isdigit():

[4] _______________

print(valid)

[1] A. Employee_number = "" || B. Employee_number = "sentinel"

[2] A. while employee_number != "": || B. while employee_number != "sentinel":

[3] A. valid = False || B. valid = True

[4] A. valid = False || B. valid = True

[1] [B] B. Employee_number = "sentinel"

[2] [A] A. while employee_number != "":

[3] [A] A. valid = False

[4] [B] B. valid = True

--------------------------------------------------------------------------

✅ Why [1] B, [2] A, [3] A, [4] B Are Correct

Employee_number = "sentinel" → ✅ B

Initializing with "sentinel" ensures the loop can start with a placeholder value before user input.

while employee_number != "": → ✅ A

The loop should continue running until the user enters an empty string (""), which is a common input sentinel for termination in validation tasks.

valid = False → ✅ A

Before validation, the default assumption should be that the input is invalid. Only if all checks pass should it be changed to True.

valid = True → ✅ B

Once the checks for length and isdigit() pass, we confirm the employee number is valid and set valid = True.

❌ Why Other Options Are Incorrect

A. Employee_number = "" → Would immediately stop the loop because the condition while employee_number != "" would fail at the start.

B. while employee_number != "sentinel" → The sentinel is not being used for termination; the empty string "" is.

B. valid = True (at initialization) → Would incorrectly assume valid input before any checks.

A. valid = False (at the end) → Would mark valid input as invalid even if all conditions are satisfied.

56
New cards

You are coding a math utility by using Python.

You are writing a function to compute roots.

The function must meet the following requirements:

If a is non-negative, return a**(1/b)

If a is negative and even, return "Result is an imaginary number"

If a is negative and odd, return -(-a)**(1/b)

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area :

def safe_root(a, b):

[1] ____________________

answer = a**(1/b)

[2] ____________________

[3] ____________________

answer = "Result is an imaginary number"

[4] ____________________

answer = -(-a)**(1/b)

return answer

[1] A. if a >= 0: B. if a % 2 == 0: C. else: D. elif:

[2] A. if a >= 0: B. if a % 2 == 0: C. else: D. elif:

[3] A. if a >= 0: B. if a % 2 == 0: C. else: D. elif:

[4] A. if a >= 0: B. if a % 2 == 0: C. else: D. elif:

[1] [A] if a >= 0:

[2] [C] else:

[3] [B] if a % 2 == 0:

[4] [C] else:

--------------------------------------------------------------------------

✅ Why [1] A, [2] C, [3] B, [4] C Are Correct

if a >= 0 → ✅ A

The first requirement specifies: "If a is non-negative, return a(1/b)".

Thus, we check for non-negative a first.

else → ✅ C (after first check)

If a is not non-negative, it must be negative. Therefore, we enter an else block to handle negative cases.

if a % 2 == 0 → ✅ B

Among negative numbers, if a is even, the requirement states: "Return 'Result is an imaginary number'".

Thus, we check for evenness using a % 2 == 0.

else → ✅ C (after even check)

If the negative number is not even, it must be odd. The requirement specifies: "Return -(-a)**(1/b)".

Thus, we use else for the odd-number case.

❌ Why Other Options Are Incorrect

B. if a % 2 == 0 (at [1]) → Would incorrectly check evenness first instead of verifying non-negativity.

D. elif (at [2], [3], [4]) → Not required because we are inside clearly separated conditional blocks (else is more readable and fits the logic tree).

A. if a >= 0 (at [2], [3], [4]) → Redundant after the first if.

57
New cards

The function must meet the following requirements:

. Anyone 18 years old or older receives a rating of "A".

. Anyone 13 or older, but younger than 18, receives a rating of "T'.

. Anyone 12 years old or younger receives a rating of "C".

. If the age is unknown, the rating is set to "C'.

You need to complete the code to meet the requirements.

Answer Area

def get_rating(age):

rating = ""

if [1]

elif [2]

elif [3]

else [4]

return rating

[1] A. age < 13: rating = "C" B. age < 18: rating = "T"

C. : rating = "A" D. age == None: rating = "C"

[2] A. age < 13: rating = "C" B. age < 18: rating = "T"

C. : rating = "A" D. age == None: rating = "C"

[3] A. age < 13: rating = "C" B. age < 18: rating = "T"

C. : rating = "A" D. age == None: rating = "C"

[4] A. age < 13: rating = "C" B. age < 18: rating = "T"

C. : rating = "A" D. age == None: rating = "C"

[1] [D] age == None: rating = "C"

[2] [A] age < 13: rating = "C"

[3] [B] age < 18: rating = "T"

[4] [C] : rating = "A"

--------------------------------------------------------------------------

✅ Why [1] D, [2] A, [3] B, [4] C Are Correct

if age == None: rating = "C" → ✅ D

The first requirement states: "If the age is unknown, the rating is set to 'C'".

Checking for None first ensures that invalid or missing age input is handled immediately.

elif age < 13: rating = "C" → ✅ A

The second requirement: "Anyone 12 years old or younger receives a rating of 'C'".

age < 13 correctly captures ages 0 through 12.

elif age < 18: rating = "T" → ✅ B

The third requirement: "Anyone 13 or older, but younger than 18, receives a rating of 'T'".

Since the previous check excludes ages under 13, this block covers 13 to 17.

else: rating = "A" → ✅ C

The final requirement: "Anyone 18 years old or older receives a rating of 'A'".

The else captures all remaining valid ages (18+).

❌ Why Other Options Are Incorrect

A (age < 13) at [1] → Would misclassify unknown ages as numeric ages.

B (age < 18) at [1] → Skips the unknown age requirement.

C (: rating = "A") at [1], [2], or [3] → Would incorrectly rate unknown or young ages as "A".

D (age == None) at [2], [3], or [4] → Should only be used first, before numeric comparisons.

58
New cards

You are developing a Python application for an online product distribution company.

You need the program to iterate through a list of products and escape when a target

product ID is found.

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

NOTE: Each correct selection is worth one point.

Answer Area

productldList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

index = 0

[1] _____________________. (index < 10) :

print(productldList[index])

if productldList[index) == 6 :

[2] _____________________.

else :

[3] _____________________.

[1] A. while || B. for || C. if || D. break

[2] A. while || B. for || C. if || D. break

[3] A. continue || B. break || C. index += 1 || D. index = 1

[1] [A] while

[2] [D] break

[3] [C] index += 1

--------------------------------------------------------------------------

while (index < 10): → ✅ A

The loop must iterate through product indices sequentially until the target product is found.

while is appropriate because we are manually controlling index.

A for loop would also work but would not align with the given index manipulation.

break → ✅ D

When the target product ID (6) is found, the loop must terminate immediately.

break exits the loop as required.

index += 1 → ✅ C

If the target is not found, we increment the index to move to the next product in the list.

❌ Why Other Options Are Incorrect

B (for) at [1] → Would iterate automatically, making manual index += 1 redundant.

C (if) at [1] → Would not create a loop, only a one-time check.

D (break) at [1] → Cannot be used to initiate a loop.

A (continue) at [3] → Would skip increment logic, causing an infinite loop.

B (break) at [3] → Would exit prematurely before reaching the target.

D (index = 1) at [3] → Would incorrectly reset the index instead of iterating forward.

59
New cards

it needs a way to find the count of particular letters in their publications to ensure that there is a good balance. It seems that there have been complaints about overuse of the letter e. You need to create a function to meet the requirements.

Answer Area

#Function accepts list of words from a file,

#and letter to search for.

#Returns count of a particular letter in that list.

def count_letter(letter, word_list):

count=0

for [1]

.

if [2]

.

count += 1

return count

word_list =[]

#word_list is populated a from file, code not shown.

letter = input("which letter would you like to count")

letter_count= count_letter(letter, word_list)

print("There are: " letter_count, " instances of " + letter)

[1] A. word_list in word: B. word in word_list:

C. word == word_list: D. word is word_list:

[2] A. word is letter: B. letter is word:

C. word in letter: D. letter in word:

[1] [B] word in word_list:

[2] [D] letter in word:

--------------------------------------------------------------------------

✅ Why [1] B, [2] D Are Correct

for word in word_list: → ✅ B

We need to iterate through each word in the list of words.

word in word_list properly extracts one word at a time for evaluation.

if letter in word: → ✅ D

Checks if the specific letter appears inside the current word.

Using in is appropriate because it evaluates membership within the string.

❌ Why Other Options Are Incorrect

A (word_list in word) → Reversed logic; checks if the entire list is inside a single word (nonsensical).

C (word == word_list) → Would compare a single word to the entire list, always False.

D (word is word_list) → Tests object identity, not membership.

A/B (is keyword at [2]) → is checks object identity, not character occurrence.

C (word in letter) → Reversed logic; checks if the entire word is a single letter.

60
New cards

You are an intern for Northwind Electric Cars. You must create a function that

calculates the average velocity of their vehicles on a 1320 foot (1/4 mile) track. The

output must be as precise as possible.

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area

#Speed calculator

distance = [1]

. (input("Enter the distance traveled in feet"))

distance_miles = distance/5280

time = [2]

#convert to miles

. (input("Enter the time elapsed in seconds"))

time_hours = time/3600

#convert to hours

velocity = distance_miles/time_hours

print("The average velocity is : ", velocity, " miles/hour")

[1] A. int B. float C. str

[2] A. int B. str C. float

[1] [B] float

[2] [C] float

--------------------------------------------------------------------------

✅ Why [1] B, [2] C Are Correct

distance = float(input(...)) → ✅ [1] B (float)

Distances can include decimal values (e.g., 1319.5 feet).

Using float ensures higher precision compared to int.

time = float(input(...)) → ✅ [2] C (float)

Time measurements are often fractional (e.g., 10.23 seconds).

float provides precise calculation for velocity.

❌ Why Other Options Are Incorrect

A (int) → Rounds values, losing precision; unacceptable for performance measurements.

C (str) → Keeps input as a string; arithmetic operations (/) would fail without conversion.

61
New cards

too long navigate it through this google docs: https://docs.google.com/document/d/1xvT8_V_YiES2-9AD9C850LobuvoXlTikdWOcKU5sMUc/edit?usp=sharing

[1] [B] == "n":

[2] [A] == "Sunday":

[3] [A] == "Thursday":

--------------------------------------------------------------------------

✅ Why [1] B, [2] A, [3] A Are Correct

[1] == "n" → ✅ B

The extra day charge applies only when the DVD is returned late. "n" (no) explicitly means not returned before 8 PM, so the condition correctly adds an extra day.

[2] == "Sunday" → ✅ A

The 30% discount applies only if the DVD was rented on a Sunday. The comparison must exactly match "Sunday" to trigger the discount.

[3] == "Thursday" → ✅ A

The 50% discount applies only if the DVD was rented on a Thursday. The exact string comparison "Thursday" ensures the correct discount.

❌ Why Other Options Are Incorrect

A ( != "n" ) would incorrectly charge an extra day for DVDs returned on time.

B or C ( >= "Sunday", <= "Thursday" ) are invalid; weekdays are not compared by greater or lesser values.

C ( is "Sunday", is "Thursday" ) checks object identity, not value equality, and may fail even if the strings are visually identical.

62
New cards

You are developing a Python application for an online game.

You need to create a function that meets the following criteria:

. The function is named update_score

. The function receives the current score and a value

. The function adds the value to the current score

. The function returns the new score

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area

[1]_______________ . [2] _______________.

current += value

[3] _______________.

[1] A. update_score B. def update_score C. return update_score

[2] A. (current, value): B. (): C. (current, value) D. ()

[3] A. pass current B. return current C. return D. pass

[1] [B] def update_score

[2] [A] (current, value):

[3] [B] return current

--------------------------------------------------------------------------

✅ Why [1] B, [2] A, [3] B Are Correct

[1] def update_score → ✅ B

Functions in Python must start with the def keyword followed by the function name. update_score is the required function name, so def update_score is correct.

[2] (current, value): → ✅ A

The function must accept two parameters: the current score and the value to add. The colon (:) properly starts the function block.

[3] return current → ✅ B

The function must return the updated score. After adding the value, returning current fulfills this requirement.

❌ Why Other Options Are Incorrect

A (update_score) is not valid; it's just a function name without the def keyword.

C (return update_score) incorrectly attempts to return the function itself, not the updated score.

B, C, D in [2] ((), (current, value), ()) are either missing parameters or syntax (:).

A, C, D in [3] (pass current, return, pass) do not return the updated score—pass does nothing, and return without a value returns None.

63
New cards

The program must accept input and return the average rating based on a five-star scale. The output must be rounded to two decimal places.

Answer Area

sum = count = done = 0

average = 0.0

while (done != -1):

rating = [1] ________.

if rating == -1:

break

sum+= rating

count+=1

average = float(sum/count)

[2] ________. + [3] ________.

[1]

A. print(" Enter next rating (1-5), -1 for done")

B. float(input(" Enter next rating (1-5), -1 for done"))

C. input("Enter next rating (1-5), -1 for done")

D. input "Enter next rating (1-5), -1 for done")

[2]

A. output("The average star rating for NetVerZleep coffee is: "

B. console.input("The average star rating for the new coffee is: "

C. printline("The average star rating for the new coffee is: "

D. print("The average star rating for the new coffee is: "

[3]

A. format(average, '.2f'))

B. format(average, '.2d'))

C. {average, '.2f'}

D. format.average .{2d}

[1] [B] float(input(" Enter next rating (1-5), -1 for done"))

[2] [D] print("The average star rating for the new coffee is:

[3] [A] format(average, '.2f'))

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → B: float(input(" Enter next rating (1-5), -1 for done"))

The rating must be converted to a numeric value for calculations, so float(input(...)) is correct.

[2] → D: print("The average star rating for the new coffee is:

Standard Python output uses print(). Other options like output or printline are invalid in Python.

[3] → A: format(average, '.2f'))

The average must be rounded to two decimal places, and format(average, '.2f') does exactly that.

❌ Why the Other Options Are Incorrect:

[1]

A only prints text and does not take input.

C & D get input as a string but do not convert it to a number.

[2]

A, B, C are not valid Python output functions.

[3]

B (.2d) formats as an integer, not a float.

C & D are syntactically invalid in Python.

64
New cards

You are creating a Python program that employees can use to keep track of their average score. The program must allow users to enter their name and current scores. The program will output the user name and the users average score. The output must meet the following requirements:

. The user name must be left-aligned.

. If the user name has fewer than 20 characters, additional space must be added to the right.

. The average score must have three places to the left of the decimal point and one place

to the right of the decimal (XXX.X).

Answer Area

name = input("what is your name?")

score = 0

count = 0

while(score != -1):

score = int(input("Enter your scores: (-1 to end)"))

if score == -1:

break

sum += score

count += 1

average_score = sum / count

print("[1] ____. , your average score is:

[2] ____. " %(name, average))

[1] A. %-20i B. %-20d C. %-20f D. %-20s

[2] A. %1.4s B. %4.1f C. %4.1s D. %1.4f

[1] [D] %-20s

[2] [B] %4.1f

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → D: %-20s

%s is used for strings.

-20 left-aligns the string and pads with spaces to ensure it occupies at least 20 characters.

[2] → B: %4.1f

%f formats floating-point numbers.

4.1 ensures three digits to the left (minimum width 4) and one digit after the decimal point, satisfying the XXX.X format.

❌ Why the Other Options Are Incorrect:

[1]

A (%-20i) and B (%-20d) are for integers, not strings.

C (%-20f) is for floating-point numbers.

[2]

A (%1.4s) and C (%4.1s) are for strings, not numbers.

D (%1.4f) gives four decimal places instead of the required one.

65
New cards

Relecloud Virtual Learning asks you to debug some code that is causing problems with their payroll. They ask you to find the source of the payroll errors. The following variables have been declared:

employee_pay = [15000, 120000, 35000, 45000]

count = 0

sum = 0

There are two errors in the following code:

for index in range(0, len(employee_pay)-1)):

count += 1

sum += employee_pay[index]

average = sum//count

print("The total payroll is:", sum )

print("The average salary is:", average)

Which code should you use to fix the errors?

Answer Area

for index in range [1]

.

count += 1

sum += employee_pay[index]

average = [2]

.

print("The total payroll is:", sum )

print("The average salary is:", average)

[1]

A. (size(employee_pay)):

B. (size(employee_pay)-1):

C. (len(employee_pay)+1):

D. (len(employee_pay)):

[2]

A. sum/count

B. sum**count

C. sum*count

[1] [D] (len(employee_pay)):

[2] [A] sum/count

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → D: (len(employee_pay))

len(employee_pay) correctly iterates through all elements in the list. There is no need to subtract 1 because range() already stops before the last index.

[2] → A: sum/count

sum/count correctly computes the average salary by dividing the total payroll (sum) by the number of employees (count).

❌ Why the Other Options Are Incorrect:

[1]

A: (size(employee_pay)) → size() is not a valid Python function for lists; len() should be used.

B: (size(employee_pay)-1) → Same issue as A; size() is invalid in Python.

C: (len(employee_pay)+1) → Would attempt to access an out-of-range index, causing an error.

[2]

B: sum**count → Exponentiation is incorrect for calculating averages.

C: sum*count → Multiplication gives the total multiplied by count, not the average.

66
New cards

You are creating a program that accepts user input. The program must cast the input into an integer. You must properly handle the error if the code cannot cast the input to an integer.

How should you complete the code? To answer, select the appropriate code segments in the answer area.

Answer Area

while True:

[1] ________.

x = int(input("Please enter a number: "))

break

[2] ________. ValueError:

print("Not a valid number. Try again...")

[1]

A. try:

B. else:

C. except:

D. raise:

E: finally:

[2] A. try:

B. else:

C. except:

D. raise: E: finally:

[1][A] try:

[2] [C] except:

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → A: try:

try: is used to attempt code execution that might raise an exception—in this case, casting user input to an integer.

[2] → C: except:

except ValueError: catches the error when the input cannot be converted to an integer and allows you to handle it gracefully.

❌ Why the Other Options Are Incorrect:

[1]

B: else: → Runs only if no exceptions occur; it cannot be placed before the try.

C: except: → Must follow try, not precede it.

D: raise: → Actively throws an exception, not handles it.

E: finally: → Runs regardless of exceptions but cannot wrap risky code directly.

[2]

A: try: → Already used to wrap risky code; cannot be used here.

B: else: → Runs when no exceptions occur; we need error handling, not success logic.

D: raise: → Would manually throw an exception instead of catching it.

E: finally: → Always executes, but it does not handle exceptions.

67
New cards

A coworker wrote a program that inputs names into a database. Unfortunately, the program reversed the letters in each name.

You need to write a Python function that outputs the characters in a name in the correct order

Answer Area

#Function reverses characters in a string.

#returns new string in reversed order.

def reverse_name(backwards_name):

forward_name = ''

for index in [1] ________.

forward_name += [2] ________.

return forward_name

print(reverse_name("leinad")) #test_ case

[1]

A. backwards_name:

B. len(backwards_name:)

C. range(0, len(backwards_name),-1):

D. range(len(backwards_name)-1,-1,-1):

[2]

A. backwards_name[index-1]

B. backwards_name[len(forward_name)-1]

C. backwards_name[len(backward_name)- len(forwardname)

D. backwards_name[index]

[1] [D] range(len(backwards_name)-1,-1,-1):

[2] [D] backwards_name[len(backward_name)- len(forwardname)

------------------------------------------------------------------------

✅ Correct Answers:

[1] → D: range(len(backwards_name)-1, -1, -1)

This correctly iterates through the string in reverse, starting from the last index (len(backwards_name)-1) down to 0, moving backward with a step of -1.

[2] → D: backwards_name[index]

Since we are already iterating in reverse using the index, we can directly access each character by its current reversed index.

❌ Why the Other Options Are Incorrect:

[1]

A: backwards_name: → Iterates directly over characters, not indexes; cannot access characters in reverse without additional logic.

B: len(backwards_name): → Not valid syntax for iteration; len() returns an integer, not an iterable.

C: range(0, len(backwards_name), -1): → Starts at 0, which makes no sense with a negative step, causing an empty range.

[2]

A: backwards_name[index-1] → Would shift all characters one position incorrectly.

B: backwards_name[len(forward_name)-1] → Always retrieves the wrong character because it depends on the growing forward_name length.

C: backwards_name[len(backward_name)- len(forwardname)] → Syntax and logic errors (backward_name is undefined, wrong calculation).

68
New cards

You are writing a function to perform safe division.

You need to ensure that a denominator and numerator are passed to the function and that

the denominator is not zero.

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area

def safe_divide(numerator, denominator):

[1] _______________.

print("A required value is missing.")

[2] _______________.

print("The denominator is zero.")

else:

return numerator I denominator

[1]

A. if numerator is None or denominator is None:

B. if numerator is None and denominator is None:

C. If numerator = None or denominator = None:

D. if numerator = None and denominator = None:

[2]

A. elif denominator == 0:

B. elif denominator = 0:

C. elif denominator != 0:

D. elif denominator in 0:

[1] [A] if numerator is None or denominator is None:

[2] [A] elif denominator == 0:

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → A: if numerator is None or denominator is None:

This correctly checks whether either the numerator or denominator is missing (None). Using or ensures that the function validates both parameters individually. The is keyword is the proper way to compare with None in Python.

[2] → A: elif denominator == 0:

This checks if the denominator is zero to prevent division by zero. The == operator is correct for numeric comparison.

❌ Why the Other Options Are Incorrect:

[1]

B (if numerator is None and denominator is None:) → Would only trigger if both are missing, failing to catch cases where only one is missing.

C (If numerator = None or denominator = None:) → Invalid syntax; If should be lowercase, and = is assignment, not comparison.

D (if numerator = None and denominator = None:) → Same syntax issue (= instead of is) and logical error (only triggers when both are None).

[2]

B (elif denominator = 0:) → Invalid syntax; = is assignment, not comparison.

C (elif denominator != 0:) → Would incorrectly print the zero-error message when the denominator is valid.

D (elif denominator in 0:) → Invalid syntax; in is used for iterable membership, not numeric comparison.

69
New cards

You must create a simple file manipulation program that performs the following actions:

. Checks to see if a file exists.

. If the file exists, displays its contents.

. If the file does not exist, 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 requirements.

Answer Area

import os

if [1].

file = open('myFile.txt')

[2].

file.close()

file= [3].

[4]. ("End of listing")

[1]

A. isfile('myFile.txt'):

B. os.exist('myFile.txt'):

C. os.find('myFile.txt'):

D. os.path.isfIIe('myFiIe.txt'):

[2]

A. output('myFile.txt')

B. print(file.get('myFile.txt'))

C. print(fiIe.read())

D. print('myFile.txt')

[3]

A. open('myFile.txt', 'a')

B. open('myFile.txt', 'a+')

C. open('myFile.txt', 'w')

D. open('myFile.txt', 'w+')

[4]

A. append

B. file.add

C. file.write

D. write

[1] [D] os.path.isfIIe('myFiIe.txt'):

[2] [C] print(fiIe.read())

[3] [B] open('myFile.txt', 'a+')

[4] [C] file.write

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → D: os.path.isfile('myFile.txt'):

Uses the correct os.path.isfile() method to check if a file exists.

[2] → C: print(file.read())

Reads and prints the file's entire contents.

[3] → B: open('myFile.txt', 'a+')

a+ opens the file for reading and appending; if it does not exist, it creates the file.

[4] → C: file.write

write() is the correct method to append text to the file.

❌ Why the Other Options Are Incorrect:

[1]

A (isfile('myFile.txt')) → Missing os.path. namespace.

B (os.exist('myFile.txt')) → No such method; should be os.path.exists().

C (os.find('myFile.txt')) → Invalid; Python's os module has no find() method.

[2]

A (output('myFile.txt')) → Not a valid Python function.

B (print(file.get('myFile.txt'))) → File objects do not have a get() method.

D (print('myFile.txt')) → Prints the file name, not its contents.

[3]

A (open('myFile.txt', 'a')) → Can append but cannot read, violating the requirement to display contents if the file exists.

C (open('myFile.txt', 'w')) and D (open('myFile.txt', 'w+')) → w modes overwrite the file.

[4]

A (append) → Not a file method; lists use append().

B (file.add) → Not valid for file objects.

D (write) → Needs to be called as file.write(), not standalone.

70
New cards

You are writing a Python program to ask the user to enter a number and determine if the number is 1 digit 2 digits, or more than 2 digits long. You need to write the program.

Answer Area

num = int(input("Enter a number with 1 or 2 digits: "))

digits = 0;

[1] ___________________________________________.

digits = "1"

[2] ___________________________________________.

digits = 2

[3] ___________________________________________.

digits = ">2"

print(digits + " digits.")

[1]

A. if num > -10 and num < 10:

B. if num > -100 and num < 100:

[2]

A. if num > -100 and num < 100:

B. elif num > -100 and num < 100:

C. if num > -10 and num < 10:

D. elif num > -10 and num < 10:

[3]

A. else:

B. elif:

[1] [A] if num > -10 and num < 10:

[2] [B] elif num > -100 and num < 100:

[3] [A] else:

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → A: if num > -10 and num < 10:

Covers all single-digit numbers, including negative single digits.

[2] → B: elif num > -100 and num < 100:

Covers all two-digit numbers (from -99 to 99) excluding single digits already checked.

[3] → A: else:

Catches any number not covered by the first two conditions, meaning more than 2 digits.

❌ Why the Other Options Are Incorrect:

[1]

B (if num > -100 and num < 100) → Includes two-digit numbers, which must be handled separately.

[2]

A (if num > -100 and num < 100) → Should be elif to avoid rechecking after the first if.

C & D (if/elif num > -10 and num < 10) → Already used in the first condition.

[3]

B (elif:) → No condition provided; else is the correct default branch.

71
New cards

Wingtip Toys is creating an interactive Times Table Helper program intended for

elementary school children.

You need to complete a function that computes and displays all multiplication table

combinations from 2 to 12.

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area

#Displays times tables 2 - 12

def times_tables():

[1] ___________________________________________.

[2] ___________________________________________.

print( row*col, end=" ")

print()

#main

times_tables( )

[1]

A. for col in range(13):

B. for col in range(2, 13):

C. for col in range(2, 12, 1):

D. for col in range(12):

[2]

A. for row in range(13):

B. for row in range(2, 13):

C. for row in range(2, 12, 1):

D. for row in range(12):

[1] [B] for col in range(2, 13):

[2] [B] for row in range(2, 13):

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → B: for col in range(2, 13):

Loops through columns from 2 to 12 (inclusive), which aligns with the requirement to display times tables from 2 to 12.

[2] → B: for row in range(2, 13):

Loops through rows from 2 to 12 (inclusive), generating all multiplication combinations.

❌ Why the Other Options Are Incorrect:

[1]

A (for col in range(13):) → Starts from 0, which is not required for times tables.

C (for col in range(2, 12, 1):) → Ends at 11 because the upper bound is exclusive; 12 must be included.

D (for col in range(12):) → Starts from 0, includes unwanted values.

[2]

A (for row in range(13):) → Starts from 0, includes unnecessary rows.

C (for row in range(2, 12, 1):) → Excludes 12 (ends at 11).

D (for row in range(12):) → Starts from 0.

72
New cards

they decide to give a bonus to all employees who do not make more than S150,000. The following formula applies to each employee

based on their base salary and a flat bonus:

New salary = current salary x 3% + a $500 bonus.

You write code that reads the employee salaries into a variable named salary_list.

You need to complete the code that applies an increase to each eligible employee's salary.

Answer Area

#Each salary in the list is updated based on increase. Employees

making.

#$150,000 or more will not get a raise.

#Salary list is populated from employee database, code not shown.

[1].

if salary_list[index] >= 150000:

[2].

salary_list[index] = (salary_list[index] * 1.03) + 500

[1]

A. for index in range(len(salary_list)+1):

B. for index in range(len(salary_list)-1):

C. for index in range(len(salary_list)):

D. for index in salary_list:

[2]

A. exit()

B. continue

C. break

D. end

[1] [C] for index in range(len(salary_list)):

[2] [B] continue

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → C: for index in range(len(salary_list)):

Iterates through all valid indices of the salary_list from 0 to len(salary_list) - 1, ensuring all salaries are checked.

[2] → B: continue

Skips the bonus calculation for employees earning $150,000 or more, continuing to the next iteration.

❌ Why the Other Options Are Incorrect:

[1]

A (for index in range(len(salary_list)+1):) → Causes an IndexError because it tries to access an index equal to the list's length.

B (for index in range(len(salary_list)-1):) → Fails to include the last employee in the list.

D (for index in salary_list:) → index becomes the salary amount, not the list index, making assignment back to the list incorrect.

[2]

A (exit()) → Terminates the entire program instead of just skipping the iteration.

C (break) → Stops the loop entirely after encountering the first ineligible salary.

D (end) → Not a valid Python statement.

73
New cards

You are creating a function to calculate admission fees by using Python. Admission fees are calculated based on the following rules:

. Anyone under age S = free admission

. Anyone age S or older who is in school = 10 USD

. Anyone age S to 17 who is not in school = 20 USD

. Anyone older than age 17 who is not in school = SO USD

How should you complete the code? To answer, select the appropriate code segments in

the answer area.

Answer Area

def admission_fee(age, school):

rate = 0

[1] _______.

rate = 10

[2] _______.

[3] _______.

rate = 20

else:

rate = 50

return rate

[1]

A. if age >= 5 and school == True:

B. if age >= 5 and age <= 17:

C. if age >= 5 and school == False:

[2]

A. elif age >= 5 and school == False:

B. else age >= 5 and school == False:

C. elif age >= 5 and school == True:

[3]

A. if age >= 5 and school == True:

B. if age >= 5 and school == False:

C. if age <= 17:

[1]A. if age >= 5 and school == True:

[2]A. elif age >= 5 and school == False:

[3]C. if age <= 17:

------------------------------------------------------------------------

✅ Correct Answers:

[1] → A: if age >= 5 and school == True:

Checks if the person is 5 or older and currently in school → 10 USD.

[2] → A: elif age >= 5 and school == False:

If not in school, checks next condition for age to determine further pricing.

[3] → C: if age <= 17:

Ensures that those 5 to 17 years old and not in school pay 20 USD, otherwise falls to else for 50 USD.

❌ Why the Other Options Are Incorrect:

[1]

B (if age >= 5 and age <= 17:) → Misses the school requirement.

C (if age >= 5 and school == False:) → Would wrongly prioritize non-school attendees first.

[2]

B (else age >= 5 and school == False:) → Invalid syntax (else cannot have conditions).

C (elif age >= 5 and school == True:) → Already covered in the first condition.

[3]

A (if age >= 5 and school == True:) → Duplicate of first condition.

B (if age >= 5 and school == False:) → Already checked in elif.

74
New cards

You develop a Python application for your company.

How should you complete the code so that the print statements are accurate? To answer, select the appropriate code segments in the answer area.

Answer Area

numList = [1,2,3,4,5]

alphaList = ["a","b",'c","d",'e"]

[1] _______________________________________________________________________.

print("The values in numList are equal to alphaList")

[2] _______________________________________________________________________.

print("The values in numList are not equal to alphaList")

[1]

A. if numList == alphaList:

B. if numList == alphaList

C. else:

D. else

[2]

A. if numList == alphaList:

B. if numList == alphaList

C. else:

D. else

[1] [A]if numList == alphaList:

[2] [C] else:

--------------------------------------------------------------------------

✅ Correct Answers:

[1] → A: if numList == alphaList:

This checks whether both lists have the same values in the same order.

[2] → C: else:

If the lists are not equal, the else block executes.

❌ Why the Other Options Are Incorrect:

[1]

B (if numList == alphaList) → Missing colon (:), causing a syntax error.

C (else:) → Cannot be used without an if statement first.

D (else) → Missing colon, also invalid syntax.

[2]

A (if numList == alphaList:) → Would duplicate the first condition; you need an else for the "not equal" case.

B (if numList == alphaList) → Again, missing colon.

D (else) → Missing colon, invalid syntax.

75
New cards

Hey everyone! 👋

I've updated the flashcards to make sure the answers and explanations are clear and aligned with actual Python behavior.

🔄 What's New

✅ Fixed Python Slicing Questions - Now matches real Python behavior & exam logic.

✅ Improved Explanations - Added notes on step behavior ([::-3]), order of operations, and random number generation.

✅ Cleaned Up Typos - Adjusted the alph string to avoid confusion.

💡 Why?

To help everyone study with clearer reasoning and avoid misunderstandings from earlier versions.

📌 What to Do

Review the updated slicing cards.

Check the added explanations if you were unsure before.

Keep practicing—we're all learning together!

Laban lang! || if you prefer pdf file here's the link to the updated one:

https://drive.google.com/file/d/1j7kV7iH_7y4QLhFmIvjO-PTZKW-wEey6/view?usp=sharing

76
New cards

Good luck sa retake bukas! Review lang, stay calm, at tiwala sa pinag-aralan. Kaya natin 'to. Certified Pythonista soon! 🐍💯

Good luck sa retake bukas! Review lang, stay calm, at tiwala sa pinag-aralan. Kaya natin 'to. Certified Pythonista soon! 🐍💯