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

Question 36

Q546 - Modules


You need a list of seven numbers of random integer values

from  1 (inclusive) to  7 (inclusive).

Which of the following code snippets should you use?


  • A
  • B
  • C
  • D
Reveal correct answer

Correct answer: D

Explanation

Topics: import random.randint() random.randrange()

             list comprehension

Try it yourself:

Explanation:

You need a list comprehension here to get a whole list of numbers.

range(1, 8) works to get a list of seven elements,

because with range() the stop is exclusive.

That is different with randint()

With randint() the stop is inclusive.

That is why you need: randint(1, 7)


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

A. This code snippet imports the random module and generates a list of seven random integer values between 1 and 8 (inclusive) using list comprehension with random.randint(1, 8). However, the range specified should be (1, 8) to include the number 7.

B. This code snippet imports the random module and generates a single random integer value between 1 and 7 (inclusive) using random.randint(1, 7). It does not create a list of seven random numbers as required in the question.

C. This code snippet imports the random module and generates a single random integer value between 1 and 7 (inclusive) using random.randrange(1, 7). It does not create a list of seven random numbers as required in the question.

D. This code snippet correctly imports the random module and generates a list of seven random integer values between 1 and 7 (inclusive) using list comprehension with random.randint(1, 7) within the specified range.

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