Python脚本不工作def

时间:2013-10-14 12:10:59

标签: python function python-3.x

下面的代码一直在跳过“TryAgainQuestion()”函数::::我真的需要一些帮助!!!它变得烦人了

    import time
    ranname = "0"

def AskForName():
    ranname = "1"
    name = input("Please enter your name: ")
    print("--------------------")
    print("  .:: ",name," ::.")
    print("--------------------")
    print("     ")
    time.sleep(2)
    Start()

def TryAgainQuestion():
    tryagain = input("Do you want to try again? (Y or N): ")
    if (tryagain == "y" or "Y"):
        AskForName()

    else:
        time.sleep(1)
        print("Made By: Daniel Parker")

def Start():
    if (ranname == "1"):
        TryAgainQuestion()

    if (ranname == "0"):
        AskForName()
Start()

谢谢, 丹

2 个答案:

答案 0 :(得分:2)

这是范围问题:第二行的ranmameAskForName函数中的global ranname不同。您需要在函数开头添加import time ranname = "0" def AskForName(): global ranname ranname = "1" 才能正确更新。

{{1}}

答案 1 :(得分:0)

正如@georgesl所建议和说的那样,它是范围问题(命名空间)

请阅读this指南,我正在通过课程附上工作代码:

import time

class myClass():

    def __init__(self):
        self.ranname = "0"

    def AskForName(self):
        self.ranname = "1"
        name = raw_input("Please enter your name: ")
        print("--------------------")
        print("  .:: ", name, " ::.")
        print("--------------------")
        print("     ")
        time.sleep(2)
        self.Start()

    def TryAgainQuestion(self):
        tryagain = raw_input("Do you want to try again? (Y or N): ")
        if (tryagain == "y"):
            self.AskForName()

        else:
            time.sleep(1)
            print("Made By: Daniel Parker")

    def Start(self):
        if self.ranname == "1":
            self.TryAgainQuestion()

        if self.ranname == "0":
            self.AskForName()

def main():

    myclass = myClass()
    myclass.Start()

   #end of main

if __name__ == "__main__":
    main()