top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of writing below statement in python - if __name__ == "__main__"

+1 vote

if __name__ == "__main__"

posted Mar 11, 2015 by Chirag Gangdev

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

So say if you are part of the main module then want to run the function main otherwise not then the following statements become handy -

if __name__ == "__main__":
answer Mar 12, 2015 by Salil Agrawal
Similar Questions
0 votes
while len(word_letters) > 0 and lives > 0:
        # letters used
        # ' '.join(['a', 'b', 'cd']) --> 'a b cd'
        print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))

        # what current word is (ie W - R D)
        word_list = [letters if letters in used_letters else '-' for letters in word]
        print('Current word: ', ' '.join(word_list))
the part which i am finding difficult to understand appears at 32:15 of the above video.
i don't know how to highlight a part of a code while posting a question on this forum. this is my first post.
if someone can help than i would be very grateful.

0 votes

I have searched for lots of tutorials and documentation on the web but, didnt find a decent one to develop extensions for Python 3 using a custom compiler (mingw32, nvcc). Please help me. PS: Dont point me to Python Documentation. It is not good for beginners. It doesnt elaborate about calls and implementation.