I searched the forum and couldn't find anything on this, so I guses I'll give this tiny topic its own thread.

What's the point of creating a main() function and calling it at the end of your program? Are there advantages to this method in comparison to just writing the code straight out in no function?

I am new to Python, but it seems to me that using main(), or whatever you want to call it, forces you to write cleaner code. Here is my argument, with no main() you create automatically global variables:

def show_x():
    """possible since x is global and is not changed"""
    print x
def double_x():
    return 2 * x
x = 3
# allows for somewhat sloppy global use of x
x = double_x()
show_x()  # 6

Wrapping the last few lines into main() makes x now local:

def show_x(x):
    """there is no global x, so it has to be passed in"""
    print x
def double_x(x):
    return 2 * x
def main():
    """main makes x local and forces you to pass it properly"""
    x = 3
    x = double_x(x)
    show_x(x)  # 6
main()

It also organizes your code a little, so you don't end up with code like this, where the lines that belong into main() are scattered all over (still in sequence though):

x = 3
 
def double_x():
    return 2 * x
 
# allows for somewhat sloppy global use of x
x = double_x()
 
def show_x():
    """possible since x is global and is not changed"""
    print x
 
show_x()  # 6

That's interesting. Thanks. I hadn't thought about that. I'm interested to hear different people's opinions. As a beginner, I want to learn good coding techniques.

This question has already been answered. Start a new discussion instead.