Life is short ~
python中创建一个函数有关键字def
def hello(name):
print "hello",name
这样就是一个函数啦,说说参数有哪几种方式:
tips:
1.函数内为参数赋新值不会改变外部的任何变量
2.函数内的变量最好跟外部的变量名字不同
1.位置参数:上面的例子就是位置参数
2.关键字参数:见名知意会有关键字
3.收集参数:一个参数接受多个值相当于 argv(from sys import argv)
def hello_again(name,pre="Mr."):
print "hello",pre,name
result:
>>> hello_again("AshinLee")
hello Mr. AshinLee
但是关键字参数要在位置参数后面,否则:
>>> def hello_again(pre="Mr.",name,):
... print "hello",pre,name
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
当然关键字参数如果你给他赋值的话也是可以改变的,只是不赋值的时候给一个默认值
收集参数需要在位置参数的后面:
def hello_again(name,pre="Mr.",*num):
print "hello",pre,name
for n in num:
print n
result:
>>> hello_again("AshinLee","Miss",1,2,3,5,6)
hello Miss AshinLee
1
2
3
5
6
Miss???? 黑人问号.jpg 演示下关键字参数是可以改变的那只是不输入的默认值
要注意的是如果关键字参数和收集参数混用,却有不输入关键字参数:
>>> hello_again("AshinLee",1,2,3,5,6)
hello 1 AshinLee
2
3
5
6
会出现和预期不符合的情况要注意
收集参数也可以收集关键字参数???
>>> def hello_again(name,*num,**age):
... print name
... print num
... print age
...
result:
>>> hello_again("AshinLee",1,2,3,5,6,pre="Mr.",sex="male")
AshinLee
(1, 2, 3, 5, 6)
{'pre': 'Mr.', 'sex': 'male'}
*num **age 位置不可调动
以上这些就是python的参数魔法啦。