博客笔记_python函数学习

之前也学习过一段时间的python基础知识,今天由于项目无法进行测试,闲来无事所以想重新温故下。我天生对代码不是很感冒才做的软件测试,但是做久了感觉软件行业是离不开代码的,索性还是抽空涉猎点代码相关的知识吧,毕竟一天在干这行就要花心思去学习这行。今天简单把python温故的重点和以前觉得的难点在此记录下:

例子可以看出,如果输入的参数个数不确定,其它参数全部通过*arg,以元组的形式由arg收集起来。对照上面的例子不难发现:
值1传给了参数x
值2,3,4,5,6.7.8.9被塞入一个tuple里面,传给了arg
def func(x,*arg):
print x #输出参数x的值
result = x
print arg #输出通过*arg方式得到的值
for i in arg:
result +=i
return result

print func(1,2,3,4,5,6,7,8,9) #赋给函数的参数个数不仅仅是2个

1 #这是函数体内的第一个print,参数x得到的值是1
(2, 3, 4, 5, 6, 7, 8, 9) #这是函数内的第二个print,参数arg得到的是一个元组
45 #最后的计算结果

如果用**kargs的形式收集值,会得到dict类型的数据,但是,需要在传值的时候说明“键”和“值”,因为在字典中是以键值对形式出现的。

但是我们也不知道参数到底会可能用什么样的方式传值啊。把上面两种方式结合起来就解决了。但是参数传递的顺序很关键。

def foo(x,y,z,*args,**kargs):
… print x
… print y
… print z
… print args
… print kargs

foo(‘qiwsir’,2,”python”)
qiwsir
2
python
()
{}
foo(1,2,3,4,5)
1
2
3
(4, 5)
{}
foo(1,2,3,4,5,name=”qiwsir”)
1
2
3
(4, 5)
{‘name’: ‘qiwsir’}

全局变量:
x = 2

def funcx():
x = 9
print “this x is in the funcx:–>”,x

funcx()
print “————————–”
print “this x is out of funcx:–>”,x

this x is in the funcx:–> 9

this x is out of funcx:–> 2

x = 2
def funcx():
global x #跟上面函数的不同之处
x = 9
print “this x is in the funcx:–>”,x

funcx()
print “————————–”
print “this x is out of funcx:–>”,x

this x is in the funcx:–> 9

this x is out of funcx:–> 9

猜你喜欢

转载自blog.csdn.net/qq_25213395/article/details/81672003
今日推荐