2014-10-30 98 views
-1

尝试创建一个程序,打印4个骰子掷骰子如果总和大于8然后小于20.当我运行这个我得到一个无限循环。我尝试设置total = 0,然后将4个骰子的总和加到while循环中,但是没有奏效。骰子滚动python

代码:

from random import randint 

def main(): 
    total = sum(diRoll()) 
    while total > 8 and total < 20: 
     print(diRoll()) 




def diRoll(): 
    dice1 = randint(1, 6) 
    dice2 = randint(1, 6) 
    dice3 = randint(1, 6) 
    dice4 = randint(1, 6) 
    diceRolls = dice1, dice2, dice3, dice4 
    return sorted(diceRolls) 


main() 
+1

我已经推出的问题回来,提供匹配的答案的人。如果您感觉需要,您可以添加解决方案作为答案。 – Blair 2014-10-30 02:09:32

回答

4

那么,你的while循环中,你永远不会设置total到一个新的价值。所以你的循环将继续对旧值进行测试,因此永远不会结束。

+0

或者它或者它会一遍又一遍地打印相同的值。 – 2014-10-30 01:24:55

+0

不,它将继续打印新值,但如果找到有效值则不会停止。试试这个:总数> 8,总数<20:total = diRoll();打印(总计) – RoBDoG 2014-10-30 01:26:09

+0

我想我解决了我的问题谢谢你们。使用我的解决方案更新了问题 – 2014-10-30 01:28:44

0

请尝试以下操作:将进入无限循环,但会打印不同的骰子排列,以满足您的总体标准。如果包括突破,它将终止

def main(): 
    while True: 
     total = sum(diRoll()) 
     if total > 8 and total < 20: 
      print(diRoll()) 
      break