Python笔记:函数的定义和作用域

本笔记整理自 udacity 课程,版权归 udacity 所有, 更多信息请访问 Udacity

定义函数

  • 默认参数: 可以向函数中添加默认参数,以便为在函数调用中未指定的参数提供默认值

    
    # 如果调用 cylinder_volume 函数时,不提供radius参数,那么radius的值为5
    
    def cylinder_volume(height, radius=5):
      pi = 3.14159
      return height * pi * radius ** 2
  • 向函数中的参数传值的方法:按照位置和按照名称

    cylinder_volume(10, 7)  # 1539.3791
    cylinder_volume(height=10, radius=7)  # 1539.3791
    cylinder_volume(radius=7, height=10)  # 1539.3791

    注意:上述第一种是常用的按照位置传值,第二种和第三种是按照名称传值

定义函数[相关练习]

  • 写一个名称为 population_density 的函数,该函数有两个参数 population 和 land_area,并根据这两个值返回人口密度。

    解决方案:

    def population_density(population, land_area):
        return population / land_area
    
    test1 = population_density(10, 1)
    expected_result1 = 10
    print("expected result: {}, actual result: {}".format(expected_result1, test1)) # expected result: 10, actual result: 10.0
    
    test2 = population_density(864816, 121.4)
    expected_result2 = 7123.6902801
    print("expected result: {}, actual result: {}".format(expected_result2, test2)) # expected result: 7123.6902801, actual result: 7123.690280065897
  • 写一个叫做 readable_timedelta 的函数,该函数有一个参数:整数 days,并返回一个表示由多少周多少天组成的字符串。例如 readable_timedelta(10) 应返回“1 week(s) and 3 day(s).”。

    解决方案:

    def readable_timedelta(days):
        weeks = int(days / 7)
        day = days % 7
        return str(weeks) + ' week(s) and ' + str(day) + ' day(s).'
    
    print(readable_timedelta(10)) # 1 week(s) and 3 day(s).

函数中的变量作用域

  • 变量作用域是指可以在程序的哪个部分引用或使用某个变量。

  • 在函数中使用变量时,务必要考虑作用域。如果变量是在函数内创建的,则只能在该函数内使用该变量。你无法从该函数外面访问该变量。

    错误的示例:

    
    # This will result in an error
    
    def some_function():
        word = "hello"
    
    print(word)

    这意味着你可以为在不同函数内使用的不同变量使用相同的名称, 正确的示例如下:

    def some_function():
      word = "hello"
    
    def another_function():
        word = "goodbye"
  • 在函数之外定义的变量依然可以在函数内访问。

    word = "hello"
    def some_function():
        print(word)
    print(word)
  • Best Practise:建议将变量定义在所需的最小作用域内。虽然函数可以引用在更大的作用域内定义的变量,但是通常不建议这么做,因为如果程序有很多变量,你可能不知道你定义了什么变量。

  • 注意:Python 不允许函数修改不在函数作用域内的变量,执行下列代码,看发生了什么

    egg_count = 0
    def buy_eggs():
        egg_count += 12 # purchase a dozen eggs
    buy_eggs()

    此时会发生错误, 导致 UnboundLocalError : 当我们尝试将函数外的一个变量的值更改或重新赋值为另一个值时,我们将遇到这个错误, 但是这个原则仅适用于整数和字符串, 列表、字典、集合、类中可以在子程序中(子函数)通过修改局部变量达到修改全局变量的目的。

猜你喜欢

转载自blog.csdn.net/tyro_java/article/details/80725956