这是我在空闲时间所做的,但出于某种原因,每当我尝试这段代码时,我都会得到一切。它的目标是从1到6中选择一个随机数。 相反,这就是我得到的
number = 1,2,3,4,5,6
import random
for i in range(20):
question= raw_input("Do you want a number from 1 to 6")
if question == "yes":
print number
elif question == "no":
print "Ok"
答案 0 :(得分:2)
number
的值是元组(1, 2, 3, 4, 5, 6)
,因此按预期工作。
如果要从该集合中选择随机数,可以尝试使用random.sample
函数
示例:
import random
result = random.sample(numbers, 1)
print result # will produce one number from the set
或者,如果您知道您将始终使用连续范围内的选择,则可以使用randint
答案 1 :(得分:2)
您要找的是random.choice
。
示例代码:
>>> import random
>>> number = [1,2,3,4,5]
>>> for i in range(3):
print(random.choice(number))
=> 5
4
2
来自python docs:
<强> random.choice(SEQ)强>
从非空序列中返回一个随机元素 起。如果seq为空,则引发IndexError。
至于代码中的问题,您没有获得任何随机生成的数字或从tuple
中选择,而只是打印整个tuple
。
答案 2 :(得分:1)
是的,你的代码中只打印了一下整数列表。要获得随机数,您需要使用random.randint
函数,如:
import random
for i in range(20):
question= raw_input("Do you want a number from 1 to 6")
if question == "yes":
print random.randint(1, 6)
elif question == "no":
print "Ok"`