函数的定义及运行特点
def funcname(parameter_list):
pass # pass只是个占位符,表示函数体
注意
def add(a,b):
return a+b
def do_sth(sth):
pass
a = add(1,2)
b = do_sth("hello")
print(a) # 3
print(b) # None
- 参数列表parameter_list可以没有
- return: value 如果没有return语句则返回None
函数必须先定义,才可以调用
def add(a,b):
return a+b
c = add(1,2)
print(c)
需要注意的是: 由于python是解释性语言,必须先定义,才可以调用
c = add(1,2)
print(c)
def add(a,b):
return a+b
NameError: name 'add' is not defined
自己调用自己,陷入了永远解不开的结
不要使用系统占用的资源(变量,方法,class)
def print(code):
print(code)
print("hello")
Traceback (most recent call last):
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 4, in <module>
print("hello")
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 2, in print
print(code)
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 2, in print
print(code)
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 2, in print
print(code)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
python内部限制了最大递归的次数,我们是可以改的
import sys
sys.setrecursionlimit(100000) # 需要注意的是虽然这里设置了100000,但是有可能达不到100000次,python内部还是做了一些限制