Python学习--函数(函数定义、函数调用)用法详解

Python学习–函数(函数定义、函数调用)用法详解

一、函数定义

1. 基本语法结构

1
2
3
4
def 函数名(参数列表):
"""文档字符串(可选)"""
函数体代码
[return 返回值]

2. 基本示例

1
2
3
4
5
6
7
8
9
10
11
# 定义一个无参数函数
def say_hello():
print("Hello, World!")

# 定义带参数的函数
def greet(name):
print(f"Hello, {name}!")

# 定义带返回值的函数
def add(a, b):
return a + b

3. 函数定义的要点

  • def 是定义函数的关键字
  • 函数名应遵循变量命名规则,通常使用小写字母和下划线
  • 括号内的参数是可选的
  • 冒号表示函数体开始
  • 函数体必须缩进(通常4个空格)
  • return 语句可选,若无则返回 None

二、函数调用

1. 基本调用方式

1
2
3
4
5
6
7
8
9
# 调用无参数函数
say_hello() # 输出: Hello, World!

# 调用带参数函数
greet("Alice") # 输出: Hello, Alice!

# 调用带返回值函数
result = add(3, 5)
print(result) # 输出: 8

2. 调用方式分类

(1) 位置参数调用

1
2
3
4
5
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")

describe_pet("dog", "Buddy") # 正确顺序
describe_pet("Buddy", "dog") # 错误顺序,逻辑不对

(2) 关键字参数调用

1
2
describe_pet(animal="hamster", name="Harry")  # 明确指定参数名
describe_pet(name="Harry", animal="hamster") # 顺序不重要

(3) 混合使用

1
describe_pet("cat", name="Whiskers")  # 位置参数在前,关键字参数在后

3. 函数调用的执行流程

  1. 程序执行到函数调用处暂停
  2. 将参数传递给函数
  3. 执行函数体内的代码
  4. 遇到 return 语句或函数体结束
  5. 返回调用处继续执行,并带回返回值(如果有)

三、函数定义与调用示例

1. 计算矩形面积

1
2
3
4
5
6
7
8
9
# 定义函数
def rectangle_area(length, width):
"""计算矩形面积"""
area = length * width
return area

# 调用函数
area = rectangle_area(5, 3)
print(f"矩形面积: {area}") # 输出: 矩形面积: 15

2. 检查数字奇偶性

1
2
3
4
5
6
7
8
9
10
11
# 定义函数
def is_even(number):
"""检查数字是否为偶数"""
if number % 2 == 0:
return True
else:
return False

# 调用函数
print(is_even(4)) # 输出: True
print(is_even(7)) # 输出: False

3. 打印乘法表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 定义函数
def print_multiplication_table(n):
"""打印n的乘法表"""
for i in range(1, 10):
print(f"{n} x {i} = {n*i}")

# 调用函数
print_multiplication_table(5)
"""
输出:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 9 = 45
"""

四、注意事项

1.函数必须先定义后调用

1
2
3
4
# 错误示例
say_hi() # NameError
def say_hi():
print("Hi!")

2.函数名不能与内置函数重名

1
2
3
# 不好的做法
def print(msg):
# 这会覆盖内置print函数

3.函数调用时参数数量必须匹配

1
2
3
4
def greet(name, age):
print(f"{name} is {age} years old")

greet("Alice") # TypeError: missing 1 required positional argument

4.函数可以多次调用

1
2
3
4
5
6
def square(x):
return x * x

print(square(2)) # 4
print(square(3)) # 9
print(square(4)) # 16

5.函数可以嵌套调用

1
2
3
4
5
6
7
def add(a, b):
return a + b

def calculate(a, b, c):
return add(a, b) * c

print(calculate(2, 3, 4)) # 20

通过合理定义和调用函数,可以使代码更加模块化、可读性更强,并提高代码的复用性。

https://mp.weixin.qq.com/s/tasm5jdzyQw8ZszqrolKOA?scene=1