5
votes

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?

5

5 Answers

15
votes

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.

8
votes

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()
3
votes

There's no such main method in python, what you have to do is:

if __name__ == '__main__':
    main()
1
votes

You are defining a function but never calling it. Hence you get no error but nothing happens. Add this add the end and it will work:

if __name__ == "__main__":
    main()
0
votes

You're not calling the function. Put main() at the bottom of your code.