[Tutor] __name__=='__main__'
Dave Angel
d at davea.name
Tue Feb 21 03:11:01 CET 2012
On 02/20/2012 06:46 PM, Michael Lewis wrote:
> Hi everyone,
>
> I am having some trouble understanding how to use __name__== '__main__'.
> Can you please give me some insight? Also, to use this, it needs to be
> within a function? Do you typically just throw it in your very last
> function or create a separate function just for this? I at first put it
> outside and after all my functions but got the error below and then put it
> inside my last function and the program ran. (side note, I have an error in
> my return for MultiplyText that I am still trying to work out, so you can
> ignore that part).
>
> Code:
Nothing magic about that line (if __name__ == "__main__"). You need to
understand the components, and why you're using them.
As others have pointed out, your original error was simply due to a
typo. Every module has a __name__ attribute. If a module is imported,
that attribute is set to the module's name. But if it is run directly
(eg. if you run python myfile.py) then it has the name "__main__"
rather than "myfile".
So if you fix the typo, and still have an error, then explain what you
run, and how, rather than saying something like "code now runs WITHOUT
me explicitly importing it."
For example:
my source file is called XXXXX.py
which looks like:
When I run the Linux commandline:
python XXXXX
I get the following results.
(and yes, I know the above won't work. I'm trying to force you to tell
us what you really did)
--
DaveA
More information about the Tutor
mailing list