简体   繁体   English

Python脚本不工作def

[英]Python Script not Working def

The code below keeps skipping the "TryAgainQuestion()" function:::: I Realy need some help!!! 下面的代码一直在跳过“TryAgainQuestion()”函数::::我真的需要一些帮助!!! It is becoming annoying 它变得很烦人

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

Thanks, Dan 谢谢,丹

It's a scope problem : the ranmame at the second line is not the same as the one in the AskForName function. 这是一个范围问题: ranmame在第二条线是不一样的人在AskForName功能。 You need to add global ranname at the beginning of the function to update properly. 您需要在函数开头添加global ranname才能正确更新。

import time
ranname = "0"

def AskForName():
    global ranname
    ranname = "1"

As suggested and said by @georgesl it's scope problem (namespace) 正如@georgesl建议和说的那样,它的范围问题(命名空间)

Please read this guide, i'm attaching a working code by a class: 请阅读指南,我正在附上一个工作代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM