0

Very basic question probably but I cannot find the answer. I have created a python program called "test.py." It contains the following code:

def test():
    print 'test'

I would like to run this program in my terminal (Mac) and have 'test' printed in the terminal. When I run the program as follows:

python test.py

it seems as if the program is executed but it does not print 'test'. How do I do that? Thanks.

user1389960
  • 433
  • 4
  • 11

5 Answers5

3

You just define test function, you need to call it. There are 2 ways:
1. Call directly:

def test():
    print 'test'

test()
  1. Call inside a main check (mostly use because when someone import your test.py, it will not call test() function):
def test():
    print 'test'

if __name__ == "__main__":
    test()
Leo Khoa
  • 897
  • 7
  • 8
2

That is because you are not actually executing anything when you call your Python script. You simply have a method that is defined inside test.py.

You will actually have to call this method somewhere. If you are looking to execute code when you call test.py, you will need to put this at the bottom of your script:

if __name__ == '__main__':
    test()

Per the documentation here

idjaw
  • 25,487
  • 7
  • 64
  • 83
1

You need to call the function. Something like this:

if __name__ == "__main__":
  test()
Rahul
  • 3,208
  • 8
  • 38
  • 68
1

you need to call that function, the easiest way to get the output, is by calling it. Add this line in somewhere before or after the function definition.

test()

However, a better practice would be put this inside an if block (reason)

if __name__ == '__main__':
    test()
Community
  • 1
  • 1
Jeffrey04
  • 6,138
  • 12
  • 45
  • 68
1
  1. if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python python test.py.

    2.You can call directly:

    def test():
        print 'test'
    
    test()
    
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
Shruti H
  • 11
  • 3