今日练习主题:函数定义与使用
今天我们将学习Python中的函数,包括如何定义函数、传递参数、返回值以及作用域等概念。
练习1:基础函数定义
# 定义一个简单的函数
def say_hello():
"""打印问候语"""
print("你好!欢迎学习Python!")
# 调用函数
say_hello()
# 带参数的函数
def greet(name):
"""向指定的人问好"""
print(f"你好,{name}!")
greet("小明")
greet("小红")
练习2:带返回值的函数
# 计算两个数的和
def add_numbers(a, b):
"""返回两个数的和"""
return a + b
result = add_numbers(5, 3)
print(f"5 + 3 = {result}")
# 计算平方
def square(number):
"""返回数字的平方"""
return number ** 2
print(f"4的平方是: {square(4)}")
练习3:默认参数值
# 带默认参数的函数
def introduce(name, age=18, city="北京"):
"""自我介绍函数"""
print(f"我叫{name},今年{age}岁,来自{city}。")
# 使用默认参数
introduce("张三")
introduce("李四", 25)
introduce("王五", 30, "上海")
# 关键字参数
introduce(age=22, name="赵六", city="广州")
练习4:可变参数
# 接受任意数量的参数
def calculate_sum(*numbers):
"""计算任意数量数字的和"""
total = 0
for num in numbers:
total += num
return total
print(f"1+2+3 = {calculate_sum(1, 2, 3)}")
print(f"1+2+3+4+5 = {calculate_sum(1, 2, 3, 4, 5)}")
# 关键字可变参数
def create_student(**info):
"""创建学生信息"""
student = {}
for key, value in info.items():
student[key] = value
return student
student1 = create_student(name="小明", age=20, grade="大三")
student2 = create_student(name="小红", age=19, major="计算机")
print(student1)
print(student2)
练习5:函数返回值多个值
# 返回多个值
def calculate_stats(numbers):
"""计算列表的最大值、最小值、平均值"""
if not numbers:
return None, None, None
max_num = max(numbers)
min_num = min(numbers)
avg_num = sum(numbers) / len(numbers)
return max_num, min_num, avg_num
scores = [85, 92, 78, 90, 88]
max_score, min_score, avg_score = calculate_stats(scores)
print(f"最高分: {max_score}, 最低分: {min_score}, 平均分: {avg_score:.2f}")
练习6:递归函数
# 递归计算阶乘
def factorial(n):
"""递归计算阶乘"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(f"5! = {factorial(5)}")
print(f"10! = {factorial(10)}")
# 递归计算斐波那契数列
def fibonacci(n):
"""递归计算第n个斐波那契数"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print("斐波那契数列前10项:")
for i in range(10):
print(fibonacci(i), end=" ")
练习7:lambda匿名函数
# 使用lambda函数
square = lambda x: x ** 2
print(f"3的平方: {square(3)}")
# 在列表排序中使用lambda
students = [
{"name": "小明", "score": 85},
{"name": "小红", "score": 92},
{"name": "小刚", "score": 78}
]
# 按分数排序
sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
print("按分数排序:")
for student in sorted_students:
print(f"{student['name']}: {student['score']}分")
练习8:函数作用域
# 全局变量和局部变量
global_var = "我是全局变量"
def test_scope():
"""测试作用域"""
local_var = "我是局部变量"
print("在函数内部:")
print(f"可以访问全局变量: {global_var}")
print(f"可以访问局部变量: {local_var}")
# 修改全局变量需要使用global关键字
global global_var
global_var = "修改后的全局变量"
test_scope()
print("在函数外部:")
print(f"全局变量: {global_var}")
# print(local_var) # 这会报错,由于local_var是局部变量
今日挑战:
创建一个完整的计算器程序,包含加减乘除等基本运算功能,使用函数来组织代码
# 挑战练习:简易计算器
def add(a, b):
"""加法"""
return a + b
def subtract(a, b):
"""减法"""
return a - b
def multiply(a, b):
"""乘法"""
return a * b
def divide(a, b):
"""除法"""
if b == 0:
return "错误:除数不能为零"
return a / b
def calculator():
"""计算器主函数"""
print("=== 简易计算器 ===")
print("支持的操作: +, -, *, /")
print("输入 '退出' 结束程序")
while True:
try:
# 获取用户输入
expression = input("
请输入表达式 (例如: 5 + 3): ")
if expression.lower() == "退出":
print("感谢使用计算器!")
break
# 解析表达式
parts = expression.split()
if len(parts) != 3:
print("请输入有效的表达式,例如: 5 + 3")
continue
num1 = float(parts[0])
operator = parts[1]
num2 = float(parts[2])
# 执行计算
if operator == "+":
result = add(num1, num2)
elif operator == "-":
result = subtract(num1, num2)
elif operator == "*":
result = multiply(num1, num2)
elif operator == "/":
result = divide(num1, num2)
else:
print("不支持的操作符!")
continue
print(f"{num1} {operator} {num2} = {result}")
except ValueError:
print("请输入有效的数字!")
except Exception as e:
print(f"发生错误: {e}")
# 运行计算器
calculator()
额外挑战:增强版计算器
# 增强版计算器(支持更多功能)
import math
def power(a, b):
"""幂运算"""
return a ** b
def sqrt(a):
"""平方根"""
return math.sqrt(a)
def enhanced_calculator():
"""增强版计算器"""
print("=== 增强版计算器 ===")
print("支持的操作: +, -, *, /, ** (幂), sqrt (平方根)")
while True:
try:
expression = input("
请输入表达式: ")
if "sqrt" in expression:
# 处理平方根运算
num = float(expression.replace("sqrt", "").strip())
result = sqrt(num)
print(f"sqrt({num}) = {result}")
else:
# 处理其他运算
parts = expression.split()
if len(parts) != 3:
print("请输入有效的表达式")
continue
num1 = float(parts[0])
operator = parts[1]
num2 = float(parts[2])
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"**": power
}
if operator in operations:
result = operations[operator](num1, num2)
print(f"{num1} {operator} {num2} = {result}")
else:
print("不支持的操作符!")
except ValueError:
print("请输入有效的数字!")
except Exception as e:
print(f"发生错误: {e}")
# 运行增强版计算器
# enhanced_calculator()
学习提示:
- def 关键字用于定义函数
- 函数可以接受参数,也可以有默认值
- return 语句用于返回结果,可以返回多个值
- *args 用于接收任意数量的位置参数
- **kwargs 用于接收任意数量的关键字参数
- lambda 用于创建匿名函数
- 注意全局变量和局部变量的作用域
明天我们将学习列表、元组和字典的进阶操作!坚持练习,你的代码会越来越模块化和可重用!
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END


















- 最新
- 最热
只看作者