第3-1课 函数

函数 - 图1

函数: 实现某些特定功能的并且被命名的代码块

函数 - 图2

函数的格式

函数 - 图3

变量的作用域

函数 - 图4

  1. #全局变量:函数外部的变量 皇帝
  2. #避部变量:函数内部的变量 将军
  3. a = 666
  4. def print_n():
  5. b=123
  6. print(b)
  7. print_n()
  8. print(b)

冲突处理

就近原则:奖在外君命有所不受

  1. a = 10
  2. def p_n():
  3. a = 999
  4. print(a)
  5. p_n()

通过global 声明改变全局变量

  1. a = 10
  2. def p_n():
  3. global a
  4. a = 999
  5. print(a)
  6. p_n()
  7. print(a)

课堂练习

函数 - 图5

第3-2课 参数与返回值

函数 - 图6

有参函数,具有可变性 Dev.step(N)

无参函数,实现特定功能

turnLeft(),turnRight()

函数 - 图7

函数 - 图8 返回进一步处理 函数 - 图9 多个return 函数 - 图10

课堂练习

函数 - 图11

  1. def fun(n):
  2. res = 1
  3. for i in range(1,n+1):
  4. res = res * i
  5. return res
  6. a = int(input())
  7. print(fun(a))