局部变量
x = 50
def func(x):
print('x is', x)
x = 2
print('change local x to', x)
func(x)
print('x is still', x)
输出:
x is 50
change local x to 2
x is still 50
global语句
x = 50
def func():
global x
print('x is', x)
x = 2
print('change global x to', x)
func()
print('value of x is', x)
输出:
x is 50
change global x to 2
value of x is 2
默认参数
只有位于参数列表尾部的参数才能被赋予默认参数值
def say(message, times=1):
print(message * times)
say('Hello')
say('Hello', 5)
输出:
Hello
HelloHelloHelloHelloHello
关键字参数
使用命名(关键字)而非位置来指定函数的参数。
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
可变参数
*param,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为param的 元祖(Tuple).
**param,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为param的字典(Dictionary)。
def total(a=5, *numbers, **phonebook):
print('a', a)
# 遍历元祖中所有项目
for single_item in numbers:
print('single_item', single_item)
# 遍历字典中的所有项目
for first_part, second_part in phonebook.items():
print(first_part, second_part)
print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
输出:
a 10
single_item 1
single_item 2
single_item 3
Jack 1123
John 2231
Inge 1560
None
DocStrings文档字符串
文档字符串也适用于模块与类
约定的是一串多行字符串,第一行以某一大写字母开始,以句号结束。
第二行为空行,第三行是任何详细的解释说明。
通过函数的__doc__属性来获取文档字符串属性
def print_max(x, y):
"""Prints the maximum of two numbers.打印两个数值中的最大值。
The two value must be integers.这两个数都应该式整数"""
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maxinum')
print_max(3, 5)
print(print_max.__doc__)
输出:
5 is maxinum
Prints the maximum of two numbers.打印两个数值中的最大值。
The two value must be integers.这两个数都应该式整数