Python(4):函数与模块

来源:互联网 发布:oracle数据库实训心得 编辑:程序博客网 时间:2024/06/05 00:11

自定义函数


无输入,无返回

def hi():    print 'hello,world!'for i in range(0,4+1):        hi()

有输入,有返回

def listSum(L):    res = 0;    for i in L:        res = res + i;    return res;L2 = [1,2,3,4,5,6,7,8,9,10];sum2 = listSum(L2);print sum2 ;L3 = [1,2.2,4.2];sum2 = listSum(L3);print sum2;
55
7.4
弱数据类型就是有这样的好处。

有输入,无返回

def printAll(X):    for x in X:        print x,X2 = ['a',1,'A','cbd',1.3,'汉字也可以'];printAll(X2);
a 1 A cbd 1.3 汉字也可以 1

输入参数有默认值

def cube1(x=1):    return x**3;a = cube1();print a;a = cube1(3);print a;

还可以做到和matlab的若nargin < 3, 又怎样怎样的效果,而且更强大。
# 参数列表def cube2(x = None, y = None, z = None):    if x == None:        x = 1    if y == None:        y = 1    if z == None:        z = 1    return x * y * z;b = cube2(y = 3, z = 2);print b

可变长的参数

# 可变长度参数# 注意extend和append的区别def myListAppend(* list1):    l = [];    for i in list1:        l.extend(i)        #l.append(i)        #l = [l i];    return la = [1,3,4];b = [2,4,6];c = myListAppend(a,b)print c
注意extend和append的区别。
[1, 3, 4, 2, 4, 6] --> extend
[[1, 3, 4], [2, 4, 6]] --> append

值传递 还是 引用传递

# 值传递 or 引用传递?def testParamRef1(x):    x = x**2; # x的平方    # return xa = 2;testParamRef1(a);print a# [] 是引用传递def testParamRef2(x):    x[0] = x[0]**2; # x的平方    # return xa = [2];testParamRef2(a);print ac = a[0];print c
第1个例子是值传递,第2个例子是引用传递。
返回结果依次是
2
[4]
4

lambda表达式

# lambda表达式fun1 = lambda x: x*xprint fun1(3)a = 3print fun1(a)print fun1fun2 = lambda : hi()fun2()
一种简单的函数定义方式。
9
9
<function <lambda> at 0x02482EF0>
hello,world!
注意,函数名代表函数的地址,要调用函数,要加“()”。


模块

# 模块# 1. import 模块名# 2. import 模块名  as 新名字# 3. from 模块 import 函数名from math import sqrtprint sqrt(9)import mathprint math.sqrt(9);import math as mprint m.sqrt(9);from math import *print abs(-3)from usemodule1 import *say()a = calcSqaure(3);print a# 模块的路径import ospath2 = os.getcwd();print path2;import syssys.path.append('D:\\Python\\python_code\\HelloWold\\src\\anotherPacket1')print sys.path# import anotherPacket1 as APfrom anotherPacket1 import *# testModule.testFun();testFun();
注意,从一个包中导入,直接import就好。如果要从别的位置导入,就还需要把那个位置加入搜索路径。

0 0
原创粉丝点击