C++猿的Python笔记03-函数
2011-08-08 16:08
375 查看
基本数据类型
整型,长整型,浮点,复数,字符串
变量
无需声明或定义类型,在需要时赋值即可使用。
函数定义
def 函数名(参数列表)
变量使用无需声明或定义类型,函数也因此没有必要定义返回类型。
默认情况下返回的是None。
函数的注意点
1. 形参是值传递
2. 为外部变量赋值,使用global关键字
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'Value of x is', x
3. 支持默认参数
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
4. 支持关键参数。即指定实参的形参。
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出
>>>
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
>>>
5. pass表示空语句块
def someFunction():
pass
6. 文档字符串 DocStrings
在函数定义后的第一个逻辑行若是字符串,则是这个函数的文档字符串。
即可被调用的说明语句。调用方法为 函数名.__doc__
文档字符串的惯例是:
一个多行字符串,它的首行以大写字母开始,句号结尾。
第二行是空行,
从第三行开始是详细的描述。
def printMax(x, y):
'''This is DocStrings.
return max number.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__
整型,长整型,浮点,复数,字符串
变量
无需声明或定义类型,在需要时赋值即可使用。
函数定义
def 函数名(参数列表)
变量使用无需声明或定义类型,函数也因此没有必要定义返回类型。
默认情况下返回的是None。
函数的注意点
1. 形参是值传递
2. 为外部变量赋值,使用global关键字
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'Value of x is', x
3. 支持默认参数
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
4. 支持关键参数。即指定实参的形参。
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出
>>>
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
>>>
5. pass表示空语句块
def someFunction():
pass
6. 文档字符串 DocStrings
在函数定义后的第一个逻辑行若是字符串,则是这个函数的文档字符串。
即可被调用的说明语句。调用方法为 函数名.__doc__
文档字符串的惯例是:
一个多行字符串,它的首行以大写字母开始,句号结尾。
第二行是空行,
从第三行开始是详细的描述。
def printMax(x, y):
'''This is DocStrings.
return max number.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__
相关文章推荐
- python学习笔记(03):函数
- Python学习笔记03 控制流语句和函数
- 03-python学习笔记:函数-调用与定义
- 我的python3基础笔记之 【定义函数】 03
- python深入笔记--装饰函数
- Python学习笔记总结(二)函数和模块
- Python3学习笔记05-字典、文件输入输出、模块、函数参数传递
- 阅读源码遇到的一些Python 函数(--小白笔记)
- Python学习笔记2(02-03):变量+运算符和表达式
- python 笔记2--函数
- python学习笔记--探索函数
- python2.7学习笔记(5) ——函数
- Python学习笔记11—函数
- day03_Python的函数
- C++猿的Python笔记02-控制流
- 初学Python的学习笔记2----dist字典,set集合,声明函数,函数参数
- 廖雪峰Python的研读笔记(一) Python基础、函数、高级特性
- Python学习笔记(七)函数的使用
- Python 笔记 : 函数
- Python.Numpy学习零碎笔记之便捷函数