无参函数

def cd_hello():
print('learn py3.0 filghting')
cd_hello()
注:调用函数的方法必须写在函数后,写在之前会报错;iOS 代码是写在哪里都可以调用的。
含参函数

局部变量
不多赘述,在一个函数内部声明的变量,该变量只存在函数局部,作用域仅为创建的函数。
x=10
def cd_hello(x):
print('x:',x)
x=2
print('x:',x)
cd_hello(x)
print('x value is',x)
输出结果:
x: 10
x: 2
x value is 10
global 语句


y=1
print('y:',y)
def change_y():
global y
print('y:',y)
y = 100
print('y:',y)
change_y()
print('y value is:',y)
输出结果
y: 1
y: 1
y: 100
y value is: 100
默认参数值

def default(msg,times=1):
print(msg * times)
default('let')
default('let',3)
输出结果:
let
letletlet
关键字参数
在函数传入参数,一般按照顺序传参,还可以采用“关键字参数=value”、“顺序+关键字参数”


可变参数
自定义输入参数的数量,可以采用“*”和“**”来实现。
- “*” 表示收集除匹配外的参数,存入数组中
- “**” 表示收集键值对,存入字典中,取值从 param.items()中取值
从此处引用直至结束所有参数
def param(a=11,*nums,**name):
print('a:',a)
for item in nums:
print('item:',item)
for key,value in name.items():
print('key: '+key+' value: '+value)
param(55,5,6,7,8,9,LET='LET1601',GSAP='GSAP1601')
输出结果:
a: 55
item: 5
item: 6
item: 7
item: 8
item: 9
key: LET value: LET1601
key: GSAP value: GSAP1601

Return 语句
return 语句就是从函数中返回,中断函数,可在中断函数时候返回数据。

DocStrings

def printLet():
'''This is a Test "for.py". 输出 LET 测试函数
test test.测试 DocStrings'''
print('Print Test')
printLet()
print(printLet.__doc__)
输出结果:
Print Test
This is a Test "for.py". 输出 LET 测试函数
test test.测试 DocStrings
注意使用方法
- 放置位置,在函数的第一行逻辑行中,文档字符串行前不能有任何逻辑语句
- 调用方法,“函数名称.doc” 注意函数名称没有括号

网友评论