函数使用和创建入门
def my_def():
return '你调用我想干啥!!!!!'
def my_pass():
pass
def my_return_more(x, y, z):
return x, y, z
print '官网的函数参考:http://docs.python.org/2/library/functions.html#abs'
print '函数的用法:%s ' % abs(-20)
print '数据类型转换:%s' % int('123')
print '调用我的时候,得先声明函数,要注意顺序,调用my_def:%s' % my_def()
print '什么都不想干 :%s' % my_pass()
x1, y1, z1 = my_return_more(1, 2, 3)
print '返回多个值:%s %s %s' % (x1, y1, z1)
千奇百怪的参数
def my(x=2):
return x;
def my_more(a, x=2):
return a, x
def my_list(l=[]):
return l;
def my_charge(number):
result = 0
for i in number:
result += i
return result
def my_charge1(*number):
result = 0
for i in number:
result += i
return result
def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
print '函数默认的参数: %s' % my()
a1, x1 = my_more(1)
print '函数多个参数的: %s %s' % (a1, x1)
l = [1, 2, 3]
print '参数List,返回:%s' % my_list(l)
print '可变参数, 返回:%s' % my_charge([1, 1, 1, 1, 2])
print '可变参数, 返回:%s' % my_charge1(1, 1, 1, 1, 2)
print '**标识DICT参数类型:%s' % person('Bob', 35, city='Beijing')
其他特性
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print '切片操作:', L[0:3]
print '切片操作:', L[:3]
print '切片操作:', L[1:3]
d = {'a': 1, 'b': 2, 'c': 3}
def diedai():
for value in d.itervalues():
print value
from collections import Iterable
def isCollections():
print 'd是否可以进行迭代', isinstance(d, Iterable)
print '迭代对象:', diedai()
isCollections()
list = range(1, 11)
print '生成List', list
函数作为返回值
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
s = lazy_sum(1, 2, 3, 4, 5)
print '函数作为返回值,执行函数:', s()