2017-05-15 62 views
0

我已經鍵入了此頁面的代碼PythonForBeginners 但是如果我執行它,它會一直持續下去,不會問我是否要再次滾動骰子。我錯過了什麼?這應該工作嗎?初學者的Python:滾動骰子

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?") 
+4

如果我在我的機器上運行此(第一去縮進'進口random'線),並輸入「無」,它停止循環。在我看來很好。 – Kevin

+1

請輸入'否'或'yes'或'y'以外的其他內容。這個循環根據用戶輸入運行 –

+0

縮進第一行('import random')後,它對我有用嗎?你確定你的注意是正確的嗎? –

回答

0

好方法之一是使用這樣一類的事情。

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

+0

嘿,非常感謝你!但我有個問題。代碼現在變得更加複雜。由於我是初學者,因此我無法真正瞭解您添加的大部分內容。所以我的問題其實是,我使用的代碼不正確? –

+0

我已經運行你的代碼。代碼運行。我不會有一個變量與是來啓動while循環。如果你看我給你的類,while循環啓動然後用戶輸入是必需的。輸入後如果是「Yes」或「Y」,則ask_something函數調用rolldice函數,就像在代碼中「滾動骰子」一樣。爲了自己的理智,我決定上課。 –