Python函数
函数
- 变量值和函数名不能相同
- 函数的注释
1
2
3
4
5
6import math
def area(r):
"""
注释内容
"""
return math.pi * r **2 - 获取函数的注释
1
2print(area.__doc__)
# 打印:注释内容 - 全局变量
- 在函数内修改全局变量时,全局变量的值并不会改变
1
2
3
4
5
6name = 'Jack'
def change_name(new_name):
name = new_name
change_name('Pipter')
print(name)
# 调用函数change_name('Pipter'),打印结果为:Jack - 如果要在函数内修改全局变量,必须使用关键字global
1
2
3
4
5
6
7
8name = 'Jack'
def change_name(new_name):
# 必须独立行声明
global name
name = new_name
change_name('Pipter')
print(name)
# 调用函数change_name('Pipter'),打印结果为:Jack
- 在函数内修改全局变量时,全局变量的值并不会改变
- main函数
- 参数默认值
1
2
3
4def greet(name, greeting = 'Hello!')
print(greeting, name + '!')
greet('Bob')
greet('Bob', 'Good morning') - 关键字参数
1
2
3
4
5
6
7
8
9
10def shop(where = 'store', what = 'pasta', howmuch = '10 pounds'):
print('I want to go to the', where)
print('and buy', howmuch, 'of', what + '.')
shop()
shop(what = 'towels')
# 打印
# I want to go to the store
# and buy 10 pounds of pasta.
# I want to go to the store
# and buy 10 pounds of towels. - 模块
- 创建模块
1
2
3
4
5
6
7
8
9
10# shapes.py
"""
模块注释
"""
def square(side):
"""函数注释1"""
rectangle(side, side)
def reactangle(height, width):
"""函数注释2"""
print(height, width) - 模块引用
- 如果使用from shapes import *,将多个模块中的所有函数都导入,存在相同函数名会有冲突
- 创建模块
- 标题: Python函数
- 作者: Henry
- 创建于 : 2026-01-03 10:07:37
- 更新于 : 2026-01-03 11:22:17
- 链接: https://mybetterworks.github.io/2026/01/03/Python函数/
- 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论