functions_basics.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """functions_basics.py - Python 函数基础示例
  2. 涵盖:普通函数、参数、返回值、默认参数、关键字参数、可变参数、
  3. 匿名函数、递归函数、作用域和闭包基础等。
  4. """
  5. def greet(name):
  6. """普通函数:接收参数并返回字符串。"""
  7. return f"Hello, {name}!"
  8. def add(a, b):
  9. """普通函数:求和。"""
  10. return a + b
  11. def power(base, exponent=2):
  12. """默认参数:exponent 默认值为 2。"""
  13. return base ** exponent
  14. def show_student(name, age, city="Beijing"):
  15. """默认参数示例。"""
  16. print(f"Name: {name}, Age: {age}, City: {city}")
  17. def print_info(name, *, age, city):
  18. """keyword-only 参数:必须使用关键字传参。"""
  19. print(f"{name}, {age}, {city}")
  20. def sum_all(*numbers):
  21. """可变参数:接收任意数量的位置参数。"""
  22. total = 0
  23. for n in numbers:
  24. total += n
  25. return total
  26. def print_scores(**scores):
  27. """关键字可变参数:接收任意数量关键字参数。"""
  28. for key, value in scores.items():
  29. print(f"{key} = {value}")
  30. def factorial(n):
  31. """递归函数:阶乘。"""
  32. if n == 1 or n == 0:
  33. return 1
  34. return n * factorial(n - 1)
  35. def outer():
  36. """闭包示例:内部函数访问外部变量。"""
  37. x = 10
  38. def inner():
  39. return x + 5
  40. return inner
  41. # 匿名函数(lambda)
  42. square = lambda x: x * x
  43. # 全局变量与局部变量
  44. count = 0
  45. def increase():
  46. global count
  47. count += 1
  48. return count
  49. # 默认参数注意事项:不要使用可变对象作为默认值
  50. # 例如:def append_item(items=[]): ...
  51. def main():
  52. print("greet('Tom') ->", greet("Tom"))
  53. print("add(3, 5) ->", add(3, 5))
  54. print("power(3) ->", power(3))
  55. print("power(3, 3) ->", power(3, 3))
  56. show_student("Alice", 18)
  57. show_student("Bob", 20, "Shanghai")
  58. print_info("Tom", age=25, city="Hangzhou")
  59. print("sum_all(1, 2, 3, 4) ->", sum_all(1, 2, 3, 4))
  60. print_scores(math=90, english=88, history=94)
  61. print("factorial(5) ->", factorial(5))
  62. closure = outer()
  63. print("closure() ->", closure())
  64. print("square(6) ->", square(6))
  65. print("increase() ->", increase())
  66. print("increase() ->", increase())
  67. # 函数作为参数传递
  68. def do_math(x, func):
  69. return func(x)
  70. print("do_math(8, square) ->", do_math(8, square))
  71. if __name__ == '__main__':
  72. main()