2014-10-30 94 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