函数
返回值
1 函数一定有返回值,如果没有指定返回值,返回None。
2 函数可以返回多个值. 多值返回实质是利用tuple做中转。
def func():
return 1,2,3,4,5
a,b,c,d,e = func()
print(b)
输出:2
Doc String
Python允许为每个函数增加一个文档字符串,这个文档字符串可以被代码访问。具体方式是在函数的第一个逻辑行定义一个字符串,用单引号括住。(不执行任何操作)。访问方式是function_name.doc.
def print_max(x,y):
'''Print the maximum of two numbers. \n Two values must be integers .'''
x = int(x)
y = int(y)
if x >y:
print('{0} is maximum '.format(x))
else:
print('{} is maximum '.format(y))
print_max(3,5)
print(print_max.__doc__)
输出:
5 is maximum.
Print the maximum of two numbers.
Two values must be integers.
lambda
一种快速定义简单函数的方法,不需要定义函数名。
形式为lambda var : logic code.
var 为输入变量,logic code为函数代码。
比如 :
def inc(n):
return n+1print(inc(10))
inc = lambda n: n+1
print(inc)
输出:1111
模块
模块是预先写好的代码,供其他代码使用。一个module是一个独立文件。每个module拥有自己的全局变量空间,函数定义,函数,均定义在其中。
import
import引入某个module对象,可以使用module.name的方式引用它的全局变量。
比如:有一个testmod.py文件然后在另外一个文件可以引入:
#testmod.py
variable1 = 1
import testmod
testmod.variable
输入:1
from import
from import引入模块中的某个(或全部)变量。被引入变量不需要module.name来访问,仅需要name.注意:不推荐引入全部变量,会引起名称空间污染。比如:
from testmod import variable1
print(variable1)
dir
列出某个模块的所有变量。比如:
import testmoddir(testmod)