# Python学习笔记之函数的定义和作用域实例详解

```
pi = 3.14159
return height * pi * radius ** 2

```

```
cylinder_volume(10, 7) # 1539.3791

```

```
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

```

```
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 ：建议将变量定义在所需的最小作用域内。虽然函数可以引用在更大的作用域内定义的变量，但是通常不建议这么做，因为如果程序有很多变量，你可能不知道你定义了什么变量。

```
egg_count = 0
egg_count += 12 # purchase a dozen eggs

```

QQ号联系： 360901061

【本文对您有帮助就好】