为什么我得到'int'对象不是可迭代错误?
问题描述:
编写一个名为roll_big的函数,它接收一个数字参数。它从1到参数的大小生成随机数;将数字加在一起。它在1滚动时停止。 1不计数,但其余数字的总和被返回。
我不明白为什么for循环对我的代码有问题。我需要解决什么问题?
import random
def roll_big(x):
count = 0
while True:
for i in random.randrange(1,x):
if i == 1:
return count
else:
count += i
答
randrange
不返回序列,它简单地返回一个数:
import random
def roll_big(x):
count = 0
while True:
i = random.randrange(1, x)
if i == 1:
return count
else:
count += i
+0
啊,谢谢你。 – 2013-04-03 20:01:49
答
random.randrange(1,x)
返回之间1和x,而不是一个列表中的单个整数。你需要修改你的代码,如下所示(注意:未经测试):
def roll_big(x):
count = 0
while True:
i = random.randrange(1, x)
if i == 1:
return count
else:
count += i
randrange的文档告诉你什么? – 2013-04-03 20:00:34