PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium

Question 39

Q442 - Functions


What is the expected output of the following code?



  • A

    ['MAR', 'JAN', 'STE']

  • B

    ['JA', 'ST']

  • C

    ['JAN', 'STE']

  • D

    ['MA', 'JA', 'ST']

Reveal correct answer

Correct answer: A

Explanation

Topics: def list slicing for append() upper()

Try it yourself:

Explanation:

The slicing in get_names() is a list slicing: names[2:]

It has a start of 2 and no end.

That means, the slicing goes from the second index (inclusive) to the end.

That will be ['Mary', 'Jane', 'Steve']

That list will be passed to the update_names() function.

The other slicing inside the for loop is a string slicing,

that will slice every element of the list

name[:3] will slice from the start to the index 3 (exclusive).

Meaning it takes the first three letters.

The upper() method will then convert those letters to uppercase letters.


Q442 (Please refer to this number, if you want to write me about this question.)

A. The code first defines a function get_names() that creates a list of names and returns a slice of the list starting from the third element ('Mary') to the end. Then, the code defines a function update_names(names) that iterates over the input list of names, takes the first three characters of each name, converts them to uppercase, and appends them to a new list. Finally, the code prints the result of calling update_names(get_names()), which returns ['MAR', 'JAN', 'STE'] as the output.

B. This choice is incorrect because it does not consider the slicing operation in the get_names() function. The update_names() function processes the names starting from the third element ('Mary'), so the output will include 'Mary', 'Jane', and 'Steve' with their first three characters converted to uppercase, resulting in ['MAR', 'JAN', 'STE'].

C. This choice is incorrect because it does not consider the slicing operation in the get_names() function. The update_names() function processes the names starting from the third element ('Mary'), so the output will include 'Mary', 'Jane', and 'Steve' with their first three characters converted to uppercase, resulting in ['MAR', 'JAN', 'STE'].

D. This choice is incorrect because it does not account for the slicing operation in the get_names() function. The update_names() function processes the names starting from the third element ('Mary'), and the first three characters of each name are converted to uppercase. Therefore, the correct output is ['MAR', 'JAN', 'STE'], not ['MA', 'JA', 'ST'].

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need