简体   繁体   中英

Python __name__() main function

I have tried looking for an answer online but couldn't find it. I am fairly new to python and wondering if you could have multiple main function in a program. For example:

ask_user = int(input('enter your choice (1 or 2): '))

if ask_user == 1:
    def print_hello():
        print('hello world')
    def main():
        print_hello()

    if __name__ == '__main__': main()

elif ask_user == 2:
    def print_hi():
        print('hi')
    def main():
        print_hi()

    if __name__ == '__main__': main()

Is this a good programing practice?

This wouldn't be considered good programming practice, no. Like index.html , the point of main() is to have a primary entry point to the program. Even if a particular language allowed that sort of thing, it would be confusing for anyone reading the code and trying to figure out where to start. For the display options, you would use separate functions with meaningful names, such as print_hello_world and print_hi , and they would both be able to be called by main() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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