CBSE Class 12 Computer Science
Question 55 of 62
Using Python Libraries — Question 8
Back to all questions 8
Question Consider the following code :
import random
print(int(20 + random.random() * 5), end = ' ')
print(int(20 + random.random() * 5), end = ' ')
print(int(20 + random.random() * 5), end = ' ')
print(int(20 + random.random() * 5))Find the suggested output options 1 to 4. Also, write the least value and highest value that can be generated.
- 20 22 24 25
- 22 23 24 25
- 23 24 23 24
- 21 21 21 21
23 24 23 24
21 21 21 21
The lowest value that can be generated is 20 and the highest value that can be generated is 24.
import random— This line imports the random module.print(int(20 + random.random() * 5), end=' ')— This line generates a random float number usingrandom.random(), which returns a random float in the range (0.0, 1.0) exclusive of 1. The random number is then multiplied with 5 and added to 20. The int() function converts the result to an integer by truncating its decimal part. Thus,int(20 + random.random() * 5)will generate an integer in the range [20, 21, 22, 23, 24]. The end=' ' argument in the print() function ensures that the output is separated by a space instead of a newline.- The next print statements are similar to the second line, generating and printing two more random integers within the same range.
The lowest value that can be generated is 20 because random.random() can generate a value of 0, and (0 * 5) + 20 = 20. The highest value that can be generated is 24 because the maximum value random.random() can return is just less than 1, and (0.999... * 5) + 20 = 24.999..., which is truncated to 24 when converted to an integer.