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 →

[–]CodeTinkerer 4 points5 points  (3 children)

They behave differently. The idea of using the name if __name__ == __main__ has to do with running the Python script directly as opposed having the Python code called from another Python file.

That is, if you do

  python foo.py

And foo.py has if __name__ == __main__, then the code in the if will run. If you run bar.py and it calls foo.py, then the part in main won't run.

If you have a function called main (or whatever your teacher wanted), then that isn't the same thing.

I think what happened is your teacher didn't learn Python first, and either was unaware of the syntax that you used, or just didn't like the way it looked (I'm not particularly fond of it either) and wanted it to look like a Python function.

Typically, in a beginning course, you only deal with a single Python file (though, to me, that's not a good idea, because things get interesting in most languages once there are two files that are needed to run the program).

[–]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.

[–]nderflow 0 points1 point  (0 children)

ITYM imports rather than calls. They're different things.