Python3笔记026 - 6.1 函数的定义和调用

第6章 函数

  • 6.1 函数的定义和调用
  • 6.2 参数传递
  • 6.3 函数返回值
  • 6.4 变量作用域
  • 6.5 匿名函数(lambda)
  • 6.6 递归函数
  • 6.7 迭代器
  • 6.8 生成器
  • 6.9 装饰器

6.1 函数的定义和调用

6.1.1 定义函数

def functionname([parameterlist]):
	['''comments''']
	[functionbody]
参数说明:
functionname:函数名称,在调用函数时使用;
parameterlist:可选参数,用于指定向函数中传递的参数;
comments:可选参数,注释的内容通常说明该函数的功能、要传递的参数的作用等。
functionbody:可选参数,称为函数体,函数被调用后要执行的功能代码。
注意:即使没有参数,也必须保留那一对括号,要不然报语法错误;
# 定义plus函数
def plus(a, b):
    '''减法函数'''
    result = a - b
    return result

6.1.2 调用函数

函数在调用之前必须先定义。

functionname([parametersvalue])
参数说明:
functionname:函数名称,
parametersvalue:可选参数,
# 函数直接被调用
def func1():
    return "This is func1's returnvalue"
def func2():
    return "This is func2's returnvalue"

f1 = func1() # 调用时带括号
f2 = func2 # 调用时不带括号

print(f1) # 打印出来的是f1函数的返回值
print(f2) # 打印出来的是f2函数的内存起始地址
print(f2()) # 打印出来的是f2函数的返回值

output:
This is func1's returnvalue
<function func2 at 0x0000025568413438>
This is func2's returnvalue
# 函数当作其他函数的参数被调用
def func1():
    print("This is func1 function")
    return "This is func1's returnvalue"
def func2(b):
    print(b)
    print(type(b))
    b()
    print(type(b()))
    print(b())
    return "This is func2's returnvalue"

print(func2(func1))

output:
<function func1 at 0x0000023C50634948>
<class 'function'>
This is func1 function
This is func1 function
<class 'str'>
This is func1 function
This is func1's returnvalue
This is func2's returnvalue
# 函数当作其他函数的返回值被调用
def func1():
    print("This is func1 function")
    return "This is func1's returnvalue"

def func2():
    return func1

f = func2()
print(f())

output:
This is func1 function
This is func1's returnvalue

敬请关注个人微信公众号:测试工匠麻辣烫

posted @ 2020-07-10 13:57  测试工匠麻辣烫  阅读(186)  评论(0编辑  收藏  举报