05 - 函数基础

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass

仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

05 - 函数基础

学习目标: 掌握函数的定义、参数和返回值


💻 代码示例

1. 定义和调用函数

python 复制代码
# 定义函数
def greet():
    print("Hello!")

# 调用函数
greet()  # Hello!

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

greet_name("Alice")  # Hello, Alice!

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

result = add(3, 5)
print(result)  # 8

2. 参数类型

python 复制代码
# 位置参数
def power(base, exp):
    return base ** exp

print(power(2, 3))  # 8

# 默认参数
def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()        # Hello, Guest!
greet("Alice") # Hello, Alice!

# 关键字参数
def introduce(name, age, city):
    print(f"{name}, {age}岁, 来自{city}")

introduce(name="Alice", age=20, city="Beijing")
introduce(city="Shanghai", name="Bob", age=21)

# 可变参数*args
def sum_all(*nums):
    return sum(nums)

print(sum_all(1, 2, 3))     # 6
print(sum_all(1, 2, 3, 4, 5))  # 15

# 关键字可变参数**kwargs
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=20, city="Beijing")

3. lambda匿名函数

python 复制代码
# 普通函数
def square(x):
    return x ** 2

# lambda函数(一行定义)
square = lambda x: x ** 2

print(square(5))  # 25

# 常用于sorted的key参数
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)  # ['apple', 'banana', 'cherry']

# 多个参数
add = lambda a, b: a + b
print(add(3, 5))  # 8

🎯 在算法题中的应用

python 复制代码
# 第1课:两数之和
def twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        if target - num in seen:
            return [seen[target - num], i]
        seen[num] = i
    return []

# 第40课:二叉树最大深度(递归)
def maxDepth(root):
    if not root:
        return 0
    return max(maxDepth(root.left), maxDepth(root.right)) + 1

# lambda在排序中应用
intervals = [[1,3], [2,6], [8,10]]
intervals.sort(key=lambda x: x[0])  # 按第一个元素排序

🎓 小结

def function_name(params): 定义函数

return value 返回值

✅ 默认参数、关键字参数

lambda 匿名函数

下一步 : 06-列表list.md


如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass

更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。

相关推荐
菜鸟丁小真19 分钟前
LeetCode hot100 -73.矩阵置零
数据结构·leetcode·矩阵·知识点总结
wearegogog12335 分钟前
动态时间规整(DTW):跨越时间维度的相似性度量
算法
ECT-OS-JiuHuaShan42 分钟前
渡劫代谢,好事多磨
数据库·人工智能·科技·学习·算法·生活
We་ct1 小时前
LeetCode 64. 最小路径和:动态规划入门实战
开发语言·前端·算法·leetcode·typescript·动态规划
CoderCodingNo1 小时前
【CSP】CSP-J 2019 江西真题 | 次大值 luogu-P5682 (适合GESP四、五级及以上考生练习)
开发语言·c++·算法
做cv的小昊1 小时前
【TJU】应用统计学——第七周作业(4.2 多元线性回归分析、4.3 可化为线性回归的曲线回归、4.4 单因子方差分析)
线性代数·算法·数学建模·矩阵·回归·线性回归·概率论
被摘下的星星1 小时前
子网de划分
网络·算法
Felven1 小时前
A. Red Versus Blue
算法
꧁细听勿语情꧂2 小时前
向下调整算法,top - k 问题,链式结构二叉树,前中后序遍历
c语言·开发语言·数据结构·算法
水蓝烟雨2 小时前
3487. 删除后的最大子数组元素和
算法·leetcode·链表