Python for Beginners:滚动骰子

时间:2017-05-15 18:32:23

标签: python while-loop

我输入了此页面中的代码PythonForBeginners 但如果我执行它,它会永远继续下去,而不是问我是否想要再次掷骰子。我错过了什么?这有用吗?

import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
    print "Rolling the dices..."
    print "The values are...."
    print random.randint(min, max)
    print random.randint(min, max)

    roll_again = raw_input("Roll the dices again?")

2 个答案:

答案 0 :(得分:0)

一种方法是使用这样的类。

list(matlist)
[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    5    9   13   17
[2,]    0    6   10   14   18
[3,]    0    7   11   15   19
[4,]    0    8   12   16   20

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    9   13   17
[2,]    2    0   10   14   18
[3,]    3    0   11   15   19
[4,]    4    0   12   16   20

[[3]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    0   13   17
[2,]    2    6    0   14   18
[3,]    3    7    0   15   19
[4,]    4    8    0   16   20

[[4]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9    0   17
[2,]    2    6   10    0   18
[3,]    3    7   11    0   19
[4,]    4    8   12    0   20

[[5]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13    0
[2,]    2    6   10   14    0
[3,]    3    7   11   15    0
[4,]    4    8   12   16    0

如果用户没有输入“是”或“Y”以及更多代码,我可以退出程序。

有关while循环的一些信息 - https://www.tutorialspoint.com/python/python_while_loop.htm

答案 1 :(得分:0)

我刚刚和初学者一样研究过同样的问题。我对你的初始代码进行了一些调整,如下所示,并且有效。

 import random
 min = 1
 min = 6

 roll_again = "yes"

 while roll_again == "yes" or roll_again == "y":
   print "You rolled..."
   print random.randint (1,6)
   roll_again = raw_input("Do you want to roll again?")

更有效和更优雅的解决方案如下:

import random 
repeat = True
while repeat:
  print ("You rolled", random.randint(1,6))
  print ("Do you want to roll again? Y/N")
  repeat = ("y" or "yes") in input().lower()