python 函数 概括
2018-05-18 本文已影响0人
little_short
函数
作用
避免重复代码
方便修改 扩展性高
保持代码一致性
def doso():
print('222')
if 1:
doso()
else:
doso()
def add(x,y):
print(x,y)
print(add([3,2],3))
import time
def logger(n):
time_format = '%Y-%m-%d $X'
time_current = time.strftime(time_format)
with open('日志记录','a') as f:
f.write('%s end action%s\n' %(time_current,n))
def action1(n):
print('starting action1...')
logger(n)
def action2(n):
print('starting action2...')
action1(2222)
函数的参数 默认参数一定跟在后面
def inf(name, age, sex='male'):
print('name %s' % name)
print('sex %s' % sex)
print('age %d' % age)
inf('xiao', 12)
inf('big', 25, 'female')
inf(age=29, name='sss')
不定长参数
def add(x, y):
print(x + y)
add(1,2)
def add(*args):
s = 0
for i in args:
s+=i
return s
print(add(1,2,3,1))
def print_info(*args, **kwargs):
print(args)
print(kwargs)
print_info('alex', 18, 'male', job='it', hobby='girls')
报错 顺序不能颠倒 print_info('alex', 'male', job='it', 18, hobby='girls')
函数的return 功能:结束函数 返回指定对象
返回什么内容 给谁
def f():
print('ok')
return 'ok'
f()
注意点
1 函数里如果没有return 会默认返回None
2 如果 return 多个对象,那么py会帮我们把这多个对象封装成一个元祖返回
函数作用域
if True:
x = 3
print(x)
x = int(2.9)
g_count = 0 #global
def outer():
enclosing
o_count = 1
def inner():
i_count = 2 # local
print(o_count)
print(i_count) # 找不到
inner()
outer()
count = 10
def outer():
print(count)
count = 100
print(count)
outer()