函数是什么
函数 = 打包的一段逻辑 + 一个名字。写一次,到处用。
def greet(name):
return f"你好,{name}!"
print(greet("WadeLy")) # 你好,WadeLy!
print(greet("小明")) # 你好,小明!
四个要点:
def关键字定义- 函数名后跟括号
(),里面是参数 - 函数体是缩进的代码块
return把结果送回调用方(没写 return 默认返回None)
没有参数 / 没有返回值
def banner():
print("=" * 30)
print(" WadeLy's Notebook")
print("=" * 30)
banner() # 调用,打印一段横幅,无返回
多个参数
def add(a, b):
return a + b
print(add(3, 4)) # 7
print(add(1.5, 2.5)) # 4.0
print(add("Hi ", "there")) # Hi there
注意:Python 不强制类型,传啥能跑就行。但写函数时心里要清楚"这个函数期望啥类型"。
return 早退
return 会立刻结束函数,可以利用它写"卫语句":
def divide(a, b):
if b == 0:
return None # 早退,避免后面除以 0
return a / b
函数也是值
在 Python 里函数是"一等公民"——可以赋给变量、传参、放进列表:
def shout(text):
return text.upper()
f = shout # 把函数赋给变量
print(f("hello")) # HELLO
actions = [shout, str.lower, str.title]
for action in actions:
print(action("Hello World"))
# HELLO WORLD
# hello world
# Hello World
这条特性是后面装饰器的基础。
文档字符串 docstring
紧跟在 def 下面、用三引号写的字符串,IDE 会显示成函数说明:
def add(a, b):
"""返回两个数相加的结果。"""
return a + b
help(add) # 终端会打印 docstring
下一步
下一篇讲**默认参数 / 关键字参数 / *args / kwargs——让函数的参数变得灵活可调。