2015-11-14 56 views
2

我不熟悉编程并尝试在Python中编写不同版本的DiceRoller游戏。方法未定义

我的代码如下,我得到一个doAgain is not defined错误。

我不确定这是简单的缩进,还是我需要在某处休息一下。

我知道这可能是一个重复,但我仍然有一点点麻烦找到这个确切的问题。

import random 
min = 1 
max = 6 

roll_again = 'yes' 

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

def doAgain(): 
    userInput = raw_input('\nWould you like to roll the dice again? \nYes \nNo') 

    if userInput == 'Yes': 
     roll_again 
    elif userInput == 'No': 
     print ('Thank you for playing!') 
    else: 
     print ('You have entered an incorrect response.') 
+2

穿戴'doAgain()'函数之前'while'回路。 –

+1

不是您当前的问题,但请注意,roll_again永远不会更新,因此您的循环将永远持续。 – Foon

回答

1

在调用它之前,您需要定义doAgain()。在while循环之上移动def doAgain():

+0

其中,您可以将'while'循环分成另一个函数,然后您可以保持顺序。只有当该函数被调用时,解释器才会查找名称。 – Berci

0

在您当前的设置中def doAgain是在您调用它之后定义的。所以它还不知道doAgain()。他说,约翰的回答是正确的。我想补充一点,如果你把东西放在一个类中,你可以把定义放在你调用它的地方之下。

例如:

class HelloWorld(): 
    # This definition automaticly get executed when the the class is executed. 
    def __init__(self): 
     print('Starting.....') 
     self.sayIt() 

    def sayIt(self): 
     print('Hello World') 

# Run class 
HelloWorld() 
+0

为此定义一个类是矫枉过正的。您可以轻松定义一个包含while循环的函数,然后调用该函数。 – chepner