The main() function appears to not work [duplicate]

I am new to Python, and I am using Python 3.3.2. I ran the following code :

import sys
def random(size=16):
    return open(r"C:\Users\ravishankarv\Documents\Python\key.txt").read(size)
def main():
    key = random(13)
    print(key)

and expected it to print the content in the key file. The program runs without errors on IDLE but nothing happens. The key is not printed.

Can someone help?


You've not called your main function at all, so the Python interpreter won't call it for you.

Add this as the last line to just have it called at all times:

main()

If you use the commonly seen:

if __name__ == "__main__":
    main()

It will make sure your main method is called only if that module is executed as the starting code by the Python interpreted, more about that is discussed here: What does if __name__ == "__main__": do?

If you want to know how to write the best possible 'main' function, Guido van Rossum (the creator of Python) wrote about it here.


Python isn't like other languages where it automatically calls the main() function. All you have done is defined your function.

You have to manually call your main function:

main()

Also, you may commonly see this in some code:

if __name__ == '__main__':
    main()