我是编程新手。我有一个作业要编写一个代码,该代码将输出 30 到 35 之间的随机数。此代码需要使用 random.seed()
、一个 for
语句和一个乘法.我知道 random.seed([x])
生成一个初始值,可以在代码的后续部分中使用。但是,我无法弄清楚在获得随机值后如何进行:
import random
random.seed(70)
print(random.random()) # This returns a value of 0.909769237923872
如何使用此值生成 30 到 35 之间的随机值?
注意:在没有上述具体说明的情况下,我已经能够编写出两段功能符合要求的代码,所以我并不是在寻找其他编写代码的方法。
最佳答案
还有另一种方法:
import random
#initial random seed based on current system time
#https://docs.python.org/2/library/random.html#random.seed
random.seed(9) #We set this so random is repeatable in testing
random_range = [30, 31, 32, 33, 34, 35]
while True:
num = int(round(random.random(),1)*100)
if num in random_range:
print num
break
种子设置为 9,因此如果您一遍又一遍地运行它,您将获得相同的随机值……从而设置一个种子。请注意,运行多次迭代是因为提到不使用像 random.choice
这样的选择关于python - 在 Python 中使用 Random.seed()、 'for' 和乘法输出 30-35 之间的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077591/