本文主要是介绍Python2.7 -- 如何使用函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
函数使用和创建入门
# coding:utf-8def my_def():return '你调用我想干啥!!!!!'def my_pass():passdef my_return_more(x, y, z):return x, y, zprint '官网的函数参考: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)
千奇百怪的参数
# coding:utf-8def my(x=2):return x;def my_more(a, x=2):return a, xdef my_list(l=[]):return l;def my_charge(number):result = 0for i in number:result += ireturn resultdef my_charge1(*number):result = 0for i in number:result += ireturn resultdef person(name, age, **kw):print 'name:', name, 'age:', age, 'other:', kwprint '函数默认的参数: %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')
其他特性
# coding:utf-8
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 valuefrom collections import Iterable
def isCollections():print 'd是否可以进行迭代', isinstance(d, Iterable)print '迭代对象:', diedai()isCollections()list = range(1, 11)
print '生成List', list
函数作为返回值
# coding:utf-8
def lazy_sum(*args):def sum():ax = 0for n in args:ax = ax + nreturn axreturn sums = lazy_sum(1, 2, 3, 4, 5)
print '函数作为返回值,执行函数:', s()
这篇关于Python2.7 -- 如何使用函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!