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.
所以,如果脚本的内容如下: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)
当你跑的时候
^{pr2}$
它将调用并输出函数的结果。或者,我尝试使用doctest,如果我想尝试小方法,则更容易管理。在
例如: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()
试试看吧:$ python mysum_script.py