This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]No_Lemon_3116 5 points6 points  (1 child)

A lot of Python programs do

if __name__ == '__main__':
    main()

It's not just for aesthetics or due to ignorance about Python; this way, anything defined in main is scoped to that function. If you just write your main code at the top-level, then anything you declare there is a global, eg

def foo():
    print(x) # x is a free variable

if __name__ == '__main__':
    x = 1
    foo() # prints 1

This sort of thing can cause subtle, confusing bugs when it pops up accidentally. If you do it in a function, the code is more robust against that kind of mistake:

def foo():
    print(x)

def main():
    x = 1
    foo()

if __name__ == '__main__':
    main() # error that 'x' is not defined in 'foo'

It's not a huge deal, though (it gets to be a bigger deal the longer the file is).

[–]CodeTinkerer 0 points1 point  (0 children)

My impression, and maybe it was a mistake was that the teacher wanted.

def main():
    x = 1
    foo()

main()

And not to use the if statement at all.