Files
2025PY/day24/07-函数的作业.py
2025-05-22 16:50:44 +08:00

69 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 1. 计算平方
def square(n):
return n * n
print(square(5)) # 输出 25
# 2. 计算两数之和
def add(a, b):
return a + b
print(add(3, 7)) # 输出 10
# 3. 判断偶数
def is_even(n):
return n % 2 == 0
print(is_even(4)) # 输出 True
print(is_even(7)) # 输出 False
# 4. 计算列表中的最大值
def find_max(lst):
return max(lst)
print(find_max([3, 5, 1, 9, 2])) # 输出 9
# 5. 计算字符串长度
def string_length(s):
return len(s)
print(string_length("hello")) # 输出 5
# 6. 计算列表中所有元素的和
def list_sum(lst):
return sum(lst)
print(list_sum([1, 2, 3, 4, 5])) # 输出 15
# 7. 计算阶乘
# 编写一个函数 factorial(n),返回 n!n 的阶乘)。
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # 输出 120
# 8. 反转字符串
def reverse_string(s):
return s[::-1]
print(reverse_string("hello")) # 输出 "olleh"
# 9. 统计列表中某个元素的出现次数
def count_occurrences(lst, target):
return lst.count(target)
print(count_occurrences([1, 2, 3, 4, 2, 2, 5], 2)) # 输出 3
# 10. 交换两个变量
def swap(a, b):
return b, a
x, y = swap(3, 7)
print(x, y) # 输出 7 3