如何更好地设置骰子程序以获得更好的输出

时间:2014-10-03 14:42:13

标签: python python-3.x

我正在尝试创建一个骰子程序,将两个骰子滚动5次并让每个骰子推出其值并添加输出组合总数。我似乎无法得到它给我合计的总数。

import random

min = 1
max = 6

def main():

     Reroll = 'y'


     while Reroll == 'y' or Reroll == 'Y':
         print('rollin...')
         print('you rolled:')
         print(random.randint(MIN, MAX))
         print(random.randint(MIN, MAX))

         again = input('Try for a higher roll? (y=yes):

main()  

在这里,我编辑了代码,现在它不会停止滚动

import random

MIN = 1
MAX = 6

def main():

     Reroll = 'y'
     while Reroll == 'y' or Reroll == 'Y':
         print('rollin...')
         print('you rolled:')
         die1 = random.randint(MIN, MAX)
         die2 = random.randint(MIN, MAX)
         total = die1 + die2
         print(die1)
         print(die2)
         print(die1, '+', die2, '=', total)

     again = input('Try for a higher roll? (y=yes)')

main()

1 个答案:

答案 0 :(得分:1)

您首先需要存储 random.randint()函数的输出,而不仅仅是打印这些:

 die1 = random.randint(MIN, MAX)
 die2 = random.randint(MIN, MAX)
 total = die1 + die2
 print(die1, '+', die2, '=', total)

您也会遇到结束循环的问题,因为您设置了本地名称again,而是测试名称Reroll。因为Reroll永远不会改变,所以循环将永远持续下去。将again替换为Reroll

Reroll = input('Try for a higher roll? (y=yes)')

这需要缩进以匹配循环中的其他行