From: What does if __name__ == "__main__": do?
When your script is run by passing it as a command to the Python interpreter,
python myscript.py
all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran.
So, if the content of your script follows:
def closest_to(l,v):
num = l[0]
diff_min = abs(l[0] - v)
for i in xrange(1,len(l)):
diff = abs(l[i] - v)
if diff < diff_min:
diff_min = diff
num = l[i]
return num
if __name__ == '__main__':
val1 = 10
val2 = 200
print 'Closes to %s, %s =' % val1, val2,
print closest_to(val1, val2)
when you run
$ python script.py
It will call and output the result of your function. Alternatively I try to use doctests, If I want to try small methods, it's easier to manage.
For example:
def mysum(*args):
"""Returns the sum of all given arguments
>>> mysum(1,2,3,4)
10
>>> mysum(1,2)
3
>>> mysum(1, -1)
0
>>> mysum(1)
1
"""
return sum(*args)
if __name__ == "__main__":
import doctest
doctest.testmod()
Run it and give it a try:
$ python mysum_script.py