Python主要功能不起作用 [英] Python main function not working

查看:97
本文介绍了Python主要功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用一些函数编写一个简单的Python程序,其中一个是 main()函数执行其他函数。但是,当我运行下面的代码没有输出。有人能告诉我他们是否在结构中看到错误吗?

I am writing a simple Python program with some functions, one of which is a main() function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?

def print1():
    print("this is also a function")
def print2():
    print("this is a function")

def main():
    print1()
    print2()


推荐答案

您需要调用 main()的。现在它只是一个定义。如果没有人使用这个词,字典中有什么用处?

You need to call main(). Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?

def print1():
    print("this is also a function")
def print2():
    print("this is a function")

def main():
    print1()
    print2()

main()

Python程序根据文件是否被导入或运行来做不同的事情。当一个文件被执行时, __ name __ 变量被设置为'__ main __'或者文件的名字。它被设置为'__ main __',如果该文件正在作为python脚本执行,并且它被设置为文件的名称(如果正在导入)。你可以使用这些信息,这样如果它只是被导入,而不是作为python脚本运行,那么你实际上不会运行任何东西:

It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the __name__ variable is set either to '__main__' or the name of the file. It is set to '__main__' if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:

if __name__ == '__main__':
    main()

这样,您可以导入该模块,并使用不带 main()的函数被调用。但是,如果以python脚本运行,则会调用 main()

That way, you can import the module, and use the functions without main() being called. If it is run as a python script, however, main() will be called.

这篇关于Python主要功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆