Python main function not working [duplicate]

2019-02-26 06:38发布

This question already has an answer here:

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

4条回答
够拽才男人
2楼-- · 2019-02-26 06:52

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

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

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.

查看更多
疯言疯语
3楼-- · 2019-02-26 07:02

I believe what you mean to be doing is

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

if __name__ == '__main__':
    print1()
    print2()

Call this script something.py and then run python something.py from your command line.

查看更多
家丑人穷心不美
4楼-- · 2019-02-26 07:04

You need to call main() in order for it to run.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-26 07:12

Add this to the bottom of your code.

if __name__ == "__main__":
    main()

See https://docs.python.org/2/library/main.html

Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.

You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.

查看更多
登录 后发表回答