Computer Science
Suppose that after we import the random module, we define the following function called diff
in a Python session :
def diff():
x = random.random() - random.random()
return(x)
What would be the result if you now evaluate
y = diff()
print(y)
at the Python prompt ? Give reasons for your answer.
Answer
import random
def diff():
x = random.random() - random.random()
return(x)
y = diff()
print(y)
Output
0.006054151450219258
-0.2927493777465524
Explanation
Output will be a floating-point number representing the difference between two random numbers. Since every call to random() function of random module generates a new number, hence the output will be different each time we run the code.
Related Questions
After importing the above module, some of its functions are executed as per following statements. Find errors, if any:
(a) square(print 3)
(b) basic.div()
(c) basic.floordiv(7.0, 7)
(d) div(100, 0)
(e) basic.mul(3, 5)
(f) print(basic.square(3.5))
(g) z = basic.div(13, 3)
Import the above module basic.py and write statements for the following :
(a) Compute square of 19.23.
(b) Compute floor division of 1000.01 with 100.23.
(c) Compute product of 3, 4 and 5. (Hint. use a function multiple times).
(d) What is the difference between basic.div(100, 0) and basic.div(0, 100)?
What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to variable NUMBER.
STRING = "CBSEONLINE" NUMBER = random.randint(0, 3) N = 9 while STRING[N] != 'L' : print(STRING[N] + STRING[NUMBER] + '#', end = '') NUMBER = NUMBER + 1 N = N - 1
- ES#NE#IO#
- LE#NO#ON#
- NS#IE#LO#
- EC#NB#IS#
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