How to generate random numbers in Python and calculate their sum?
To generate random numbers and calculate their sum in Python, you can achieve it by using functions in the random module.
Firstly, the random module needs to be imported.
import random
Next, you can use the randint function in the random module to generate a random number. This function takes two parameters, indicating the range in which to generate the random number. For example, to generate a random integer between 1 and 10, you can use the following code:
random_number = random.randint(1, 10)
Next, you can use a loop structure to generate multiple random numbers and then add them together. For example, the following code generates 10 random integers between 1 and 10 and then adds them together.
sum = 0
for i in range(10):
random_number = random.randint(1, 10)
sum += random_number
Finally, you can output the result of the sum.
print("求和结果为:", sum)
The complete code is shown below:
import random
sum = 0
for i in range(10):
random_number = random.randint(1, 10)
sum += random_number
print("求和结果为:", sum)
After running the code, you will get the sum of 10 random integers between 1 and 10.