Member Avatar for Mouche

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
Member Avatar for Mouche

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.

Something like main() makes for cleaner code, a little extra work. I should use it more often.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.