函数
# 函数
# 函数定义
函数通过关键字 def
## 函数定义
def say_hello():
print('hello function')
## 函数调用
say_hello()
# 函数参数
在定义函数 时给定的名称称作_“形参”(Parameters),在调用函数时你所提供给函数的值称作“实 参”_(Arguments)。
def print_max(a, b):
if (a > b):
print(a)
elif (b > a):
print(b)
else:
print("%d, %d" % (a, b))
print_max(3, 5)
print_max(5, 3)
print_max(5, 5)
x = 4
y = 6
print_max(x, y)
# 局部变量
def func_local(x):
print('x is now, %d' % x)
x = 30
print('x in function now, %d' % x)
x = 50
func_local(x)
print('x out of function, %d' % x)
# global
全局变量
x = 50
def func_global():
global x
print('global x is %d' % x)
x = 30
print('global x is %d' % x)
func_global()
print('global x is %d, out of function' % x)
# 默认参数
def func_default(message, time=1):
print(message * time)
func_default('hello')
func_default('hello world', 5)
def func_default(message, time=1):
,
func_default('hello')
如果没给实参, 那么time 就会有默认值
# 关键字参数
def func_kw(a, b=3, c=1):
print('a is', a, 'b is', b, 'c is', c)
func_kw(3, 7)
func_kw(2, c=5)
func_kw(c=50, a=100)
# 可变参数
def func_var(a=5, *numbers, **phonebooks):
print('a', a)
for i in numbers:
print('numbers,', i)
print('phonebooks')
for k, v in phonebooks.items():
print('k:', k, 'v:', v)
## 1,2,3 会形成元组,填入 number
## Jack=1123, John=2231, Inge=1560 会形成字典, 填入phonebooks
func_var(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560)
# 返回值
def maximum(x, y):
if x > y:
return x
elif x == y:
print('x ==y')
else:
return y
print(maximum(23, 42))
print(maximum(42, 23))
print(maximum(42, 42))
如果 return 语句没有搭配任何一个值则代表着 返回 None 。 None 在 Python 中一 个特殊的类型,代表着虚无。举个例子, 它用于指示一个变量没有值,如果有值则它的值便 是 None(虚无) 。 每一个函数都在其末尾隐含了一句 return None ,除非你写了你自己的 return 语句。
# docstring
def maximum(x, y):
"""
:param x:
:param y:
:return: 两数较大值,返回None
"""
if x > y:
return x
elif x == y:
print('x ==y')
else:
return y
print(maximum(23, 42))
print(maximum(42, 23))
print(maximum(42, 42))
print(maximum.__doc__)