- 定义函数使用def语句
如 def hello(name):
return ‘hello,’ + name + ‘!’
执行以上代码之后,会有一个以hello命名的函数
以下是两种不同的表达:前者是用return表达式介绍函数,后者是用print,直接调用函数
def hello(name):
return 'hello, '+ name + '!'
print(hello('Holly'))
def hello(name):
print('hello,',name)
hello('Holly!')
输出结果为hello,Holly!
稍微复杂一点的例子有
求长方体的体积
def volume(length,width,height):
return length * width * height
l = 2
w = 3
h = 5
print('length=',l,'width=',w,'height=',h,'volume=',volume(l,w,h))
pythoncode python3 holly_03_19.py
length= 2 width= 3 height= 5 volume= 30
调用函数。只有调用函数,才能让函数执行。嵌套关系,一步步执行
def reduce(arg1, agr2):
print("123")
return agr2-arg1
def hello():
print("hello")
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2 #30
print ("函数内 : ", total)
mc = multiply(arg1,arg2) # 2,这里调用multiply函数
return total + mc
def multiply(arg1, arg2):
print("hhhh")
hello() #200
return arg1*arg2 + reduce(arg1,arg2)
# 调用sum函数
total = sum( 10, 20 )
# 1,先调用sum函数,找到对应的函数,没有调用的暂时不返回值
print ("函数外 : ", total)
➜ pythoncode python3 holly_03_19.py
函数内 : 30
hhhh
hello
123
函数外 : 240
return后面没有指定值,返回为none
def test():
print('this is a dog')
return
print('this is a cat')
x = test()
print(x)
➜ pythoncode python3 holly_03_19.py
this is a dog
None