Python 随机没有函数刷新而不运行



我的函数如下。我正在输入 2 个 no,在它们之间找到随机的 no,然后将它们全部相乘。

start = int(input("Enter start value"))
end =   int(input("Enter end value"))
import random
numlist = random.sample(range(start,end),10)
print("list of random nos are" + str(numlist))
from functools import reduce
prod = reduce(lambda x,y: x*y, numlist)
print("the product of random nos: {0} is {1}".format(numlist,prod))

输出如下

Enter start value7
Enter end value89
list of random nos are: [58, 13, 47, 43, 44, 56, 86, 14, 25, 71]
the product of random nos: [51, 30, 7, 25, 49, 29, 35, 54, 27, 67] is 1300840136977500

我的问题是 a( 为什么随机 nos 列表会发生变化(第一行[58,13..第二行[51,30...即使我没有再次运行这numlist = random.sample(range(start,end),10)行代码。

这是怎么回事?

我刚刚添加了print(numlist),随机数对我来说没有改变。试试这个

end =   int(input("Enter end value"))
import random
numlist = random.sample(range(start,end),10)
print(numlist)
from functools import reduce
prod = reduce(lambda x,y: x*y, numlist)
print("the product of random nos: {0} is {1}".format(numlist,prod)) 

使用函数,以便在每次调用函数时重新生成随机值。

>>> f = random.random()
>>> f
0.27924394986694034
>>> def randomizer():   return random.random()
...
>>> randomizer()
0.10425940372082476
>>> randomizer()
0.5703202999521394```

相关内容

最新更新