循环一个答案Python



我有一个答案,我想循环10次。代码现在看起来是这样的:

top = int(input("Please tell us the highest number in the range: "))
bottom = int(input("Tell us the lowest number in the range: "))
print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)

这给我留下了答案:
请告诉我们该范围内的最高数字:100
告诉我们范围内的最低数字:10
蝙蝠侠从10到100的中选择57

现在我想让蝙蝠侠从这个范围内随机抽取10个数字。我是这样想的:

print("Batman picks the number",random.sample((bottom,top), 10),"from the range between",bottom,"and",top)

问题是我收到一条错误消息,上面写着:ValueError:样本大于总体
我必须填充什么?我需要另一个变量吗?提前谢谢。问候Thomas

我假设您想要的是:

print("Batman picks the number",random.sample(range(bottom,top), 10),"from the range between",bottom,"and",top)

也就是说,我假设你正在寻找没有替代品的样品。如果你想每个号码打印一行,你可以这样做:

for number in random.sample(range(bottom,top):
    print("Batman picks the number", number, 10),"from the range between",bottom,"and",top)

由于使用错误,您收到了关于population的错误。它不期望有一个包含下限和上限的元组,而是一个可以随机选择的元素列表。应该这样使用:

>>> import random
>>> random.sample(range(0, 20), 10)
[7, 4, 8, 5, 19, 1, 0, 12, 17, 11]
>>> 

或者将任何项目列表作为第一个变量。

我认为您需要使用xrange(bottom,top)而不仅仅是(bottom,top),这将从底部到顶部填充总体,然后是随机的。sample(xrange(bottom,top),10)现在可以返回从填充的元素中选择的10个随机元素的列表,保持原始总体不变。

只需使用while循环:

num = 10
while num>0:
    print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)
    num -= 1

最新更新