Python入门宝典:函数、列表元组与字典详解
一、函数:代码的魔法工具箱
1.1 函数是什么?
函数就像厨房里的多功能料理机——把食材(参数)放进去,按下按钮(调用函数),就能得到美味的果汁(返回值)。例如:
# 制作苹果汁的函数
def make_juice(fruit):
return fruit + "汁"
print(make_juice("苹果")) # 输出:苹果汁
1.2 函数格式详解
函数的标准结构包含三要素:
def 函数名(参数): # 定义函数
"""函数说明文档""" # 使用三个引号添加注释
函数体
return 返回值 # 返回结果
1.3 参数花样用法
默认值参数(点餐示例)
def order(food, count=1): # 默认点1份
print(f"点了{count}份{food}")
order("盖浇饭") # 输出:点了1份盖浇饭
order("麻辣烫", 3) # 输出:点了3份麻辣烫
关键字参数(避免顺序错误)
def register(name, age):
print(f"姓名:{name}, 年龄:{age}")
register(age=18, name="小明") # 明确指定参数对应关系
1.4 返回值妙用
返回多个值(解包示例):
def calculate(a, b):
return a+b, a-b, a*b
sum_result, sub_result, mul_result = calculate(5, 3)
print(f"和:{sum_result}, 差:{sub_result}, 积:{mul_result}")
1.5 变量作用域实战
global_var = "全局变量"
def test_scope():
local_var = "局部变量"
global global_var # 声明使用全局变量
global_var = "修改后的全局变量"
test_scope()
print(global_var) # 输出:修改后的全局变量
# print(local_var) # 这里会报错,局部变量无法在外部访问
1.6 函数高级技巧
链式调用(字符串处理)
text = " Hello, World! "
result = text.strip().lower().replace("world", "Python")
print(result) # 输出:hello, python!
嵌套调用(温度转换)
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
def print_temperature(c):
f = celsius_to_fahrenheit(c)
print(f"{c}摄氏度 = {f:.1f}华氏度")
print_temperature(25) # 输出:25摄氏度 = 77.0华氏度
递归示例(阶乘计算)
def factorial(n):
if n == 1: # 基线条件
return 1
else: # 递归条件
return n * factorial(n-1)
print(factorial(5)) # 输出:120
二、列表与元组:数据收纳神器
2.1 对比理解
-
列表:像可以随时增减物品的购物车 🛒
-
元组:像固定尺寸的收纳盒,一旦装满就不能修改 📦
2.2 列表操作大全
# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
# 访问元素
print(fruits[1]) # 输出:香蕉(索引从0开始)
# 切片操作
print(fruits[0:2]) # 输出:['苹果', '香蕉']
# 遍历列表
for fruit in fruits:
print(f"今天吃:{fruit}")
# 增删元素
fruits.append("葡萄") # 追加
fruits.insert(1, "芒果") # 插入
fruits.remove("香蕉") # 删除
del fruits[0] # 删除索引0的元素
2.3 元组不可变示例
# 创建元组
dimensions = (1920, 1080)
# 尝试修改会报错
# dimensions[0] = 2560 # 报错:元组不可修改
# 解包使用
width, height = dimensions
print(f"分辨率:{width}x{height}")
三、字典:高效的信息检索表
3.1 字典是什么?
字典就像电子通讯录,通过名字(key)快速找到联系方式(value)
3.2 字典操作实战
# 创建字典
student = {
"name": "小明",
"age": 18,
"courses": ["数学", "英语"]
}
# 查找元素
print(student.get("name", "未知")) # 输出:小明
# 新增/修改
student["gender"] = "男" # 新增性别
student["age"] = 19 # 修改年龄
# 删除元素
del student["courses"] # 删除课程信息
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
# 合法key示例
valid_dict = {
1: "数字",
"two": "字符串",
(3,4): "元组" # 元组可作为key
}
3.3 字典使用技巧
# 统计词频
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # 输出:{'apple':3, 'banana':2, 'orange':1}
四、开发小贴士
-
选择数据结构:
-
需要修改数据 ➡️ 列表
-
数据固定不变 ➡️ 元组
-
快速键值查找 ➡️ 字典
-
-
函数设计原则:
-
一个函数只做一件事
-
函数长度不超过一屏
-
使用有意义的命名
-
-
字典键选择:
-
优先使用字符串
-
需要组合键时使用元组
-
避免使用复杂对象作为键
-
掌握这些基础知识,你已经迈出了成为Python开发者的重要一步!接下来可以通过实际项目练习,逐步提升编程能力。遇到问题多查文档,善用print()调试,编程之路越走越宽广!