Python初学者:滚动di

2024-09-29 11:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经从这个页面输入了代码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?")

Tags: the代码importrandom页面minmaxyes
2条回答

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

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()

如果用户没有输入“Yes”或“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?")

更高效和优雅的解决方案是:

^{pr2}$

相关问题 更多 >