原创文章,欢迎转载。转载请注明:转载自 祥的博客
原文链接:http://blog.csdn.net/humanking7/article/details/45276889
函数是实现模块编程的基本组件
Python用 def
语句定义函数
def functionName( arguments ):
suite #空四格
每个Python函数都有一个返回值,默认为 None
,也可以使用 return value
明确定义返回值。
def
语句会创建一个函数对象,并同时创建一个指向函数的对象引用
eg:
>>def testFunc(arg):
print arg
>>callable(testFunc)
True
>>testFunc("Hello World!")
Hello World!
Python有众多内置函数
Python标准库拥有众多内置模块,这些模块拥有大量函数
.py
文件,其拥有自定义的函数与类及变量等import
语句进行,后跟模块名称 ( 不能指定模块文件名的后缀,即 .py
)eg:
>>> import random
>>> x = random.choice(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> print x
c
#
—> 可以从一行的任意地方开始 ( 注意Python中有些独特的注释可以当作 Python文档 )\
—> 反斜线'''
—> ( 三个单引号 )闭环操作符,单一语句跨多行。用 __doc__
调用。if、 while
等,以冒号结束;
—> 以分号作为分隔符import
)文档
Python允许通过 __doc__
动态获得文档字串
>>> str.__doc__
"str(object='') -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object."
>>> print str.__doc__ #这样显示更好看一点
str(object='') -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
缩进
统一缩进4个字串
_x
)不会被 from modul import *
语句导入__x__
)是系统变量名,对解释器有特殊的意义__x
)是类的本地变量_
)用于保存最后表达式的结果(就像Matlab中的ans一样)注意: 变量名没有类型,对象才有!!!