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
- import random
- nums = [random.randint(1, 8) for i in range(1, 8)]
-
B
- import random
- nums = random.randint(1, 7)
-
C
- import random
- nums = random.randrange(1, 7)
-
D
- import random
- nums = [random.randint(1, 7) for i in range(1, 8)]
Reveal correct answer
Correct answer: D
Explanation
Topics: import random.randint() random.randrange()
list comprehension
Try it yourself:
- import random
- print([random.randint(1, 7) for i in range(1, 8)])
- # e.g. [6, 3, 7, 5, 1, 4, 2]
- print([random.randint(1, 8) for i in range(1, 8)])
- # e.g. [6, 7, 3, 1, 8, 7, 8]
- print(random.randrange(1, 7)) # e.g. 6
- print(random.randint(1, 7)) # e.g. 7
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.
