所以我正在制作一个随机数生成器,我希望能够打印总数。我以前做过这个,但有所有随机数,如:die1 = random.randrange(1, 10)
这是我的代码:
import random
while True:
dicenumber = raw_input('How many die are you rolling?>')
dicesize = raw_input('What size die are you rolling?>')
rolls = int(dicenumber)
while rolls > 0:
print random.randrange(1, int(dicesize))
#print the total of the numbers?
rolls = rolls - 1
答案 0 :(得分:2)
你可以使用生成器表达式和sum
builtin:
dicesize = int(dicesize)
dicenumber = int(dicenumber)
print sum(random.randrange(1, dicesize) for _ in range(dicenumber))
基本上,生成器表达式循环dicenumber
次,每次产生一个新的随机整数sum
。 Sum选取随机整数并将它们全部加在一起,直到生成器停止生成。此时,总计从sum
返回并打印。
答案 1 :(得分:-1)
根据我的理解,这是答案:
import random
dicenumber=5 # set to some value >0
while dicenumber > 0: # while True is a bad idea
dicenumber = raw_input('How many die are you rolling?>')
dicenumber = int(dicenumber)
if dicenumber > 0:
dicesize = raw_input('What size die are you rolling?>')
rolls = int(dicenumber)
sum=0
while rolls > 0:
sum=sum + random.randrange(1, int(dicesize))
#print the total of the numbers?
rolls = rolls - 1
print "the sum is=" , sum
else:
break
确保正确缩进代码。此外,你是否意识到你的原型中有一个永远运行的while循环?你也必须清理我的代码。我已经多次计算int(dicenumber),这是不必要的。