[英]Python for Beginners: Roll the dice
我已经从该页面输入了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?")
做到这一点的一种方法是使用这样的类。
import random
class RollTheDice(object):
def __init__(self):
self.min = 1
self.max = 6
super(RollTheDice, self).__init__()
def ask_something(self):
while True:
userInput = str(raw_input("Roll Again? Yes or No" + "\n"))
if (userInput == "Yes" or userInput == 'Y'):
self.rollDice()
else:
print("You didn't type 'Yes' or 'Y' no roll for you. Bye....")
exit()
def rollDice(self):
print "Rolling the dices..."
print "The values are...."
print random.randint(self.min, self.max)
print random.randint(self.min, self.max)
RollTheDiceObject = RollTheDice()
RollTheDiceObject.ask_something()
如果用户没有使用更多代码键入“是”或“ Y”,则我退出程序,您可以使其更智能。
关于while循环的一些信息-https: //www.tutorialspoint.com/python/python_while_loop.htm
我刚和初学者一样在研究相同的问题。 我对您的初始代码做了一些调整,如下所示,它可以正常工作。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.