The study of parameter of function in Python(20170908)
positinal parameter
def xxx(e_1):
return e_1*e_1*e_1
e = int(input(‘please enter a number:’))
print(xxx(e))
the e is positional parameter, the function xxx(e_1) only have a parameter
default parameter
def function_name(parameter_1,parameter_2,…)
the first parameter must existen, the second is a default parameter
def register(name,gender,age,major = ‘cs’):
print(name,gender,age,major)
print(register(‘yuhanyu’,’male’,22))
print(register(‘amu’,’female’,23,’math’))
the ‘major’is a default parameter
should notice,the default parameter must point the immutable object
What is immutable object
def add_end(end = None):
if end is None:
end = []
end.append(‘end’)
return end
print(add_end(None))
print(add_end(None))
variable parameter
def x_xx_xxx(*num):
sum = 0
for x in num:
sum = sum + x*x
return sum
e = int(intput(‘please enter a number to test the program:’)
print(x_xx_xxx(1))
print(x_xx_xxx(1,2))
print(x_xx_xxx(1,2,3))
It existens a new way to use the variable parameter
when there are list or tuple
nums = [1,2,3,4]
print(x_xx_xxx(*nums))
the *nums means that the all parameter of the list of nums can be transfered to
the function x_xx_xxx as variable parameter
keyword parameter
example
def personnal_information(name,age,gender,**kwp):
print(‘name=’,name,’age=’,age,’gender=’,gender,’other=’,kwp)
print(personnal_information(‘yuhanyu’,22,’male’))
print(personnal_information(‘amu’,23,’famale’,major = ‘cs’))
that means the keyword parameter can extend the function
the function can recieve more parameter
there is a new way to transfer dict after it is done
more = {‘major’:’cs’,’come_from’:’guilin’}
print(personnal_information(‘yuhanyu’,22,’male’,**more))
named keyword parameter
def(para1,para2,*,nkp1,nkp2):
or def(para1,para2,*variable_parameter,nkp1,nkp2):
must send a parameter to the named keyword parameter
def person(name, age, *, city, job):
print(name, age, city, job)
print(person(‘yuhanyu’,22,city = ‘guilin’,job = ‘cs’))
another way
def person(name, age, *args, city, job):
print(name, age, args, city, job)
person(‘amu’,23,city = ‘guangzhou’,job = ‘cs’)
本文详细介绍了Python中函数的各种参数类型,包括位置参数、默认参数、可变参数、关键字参数及命名关键字参数等,并通过实例展示了如何使用这些参数。
72万+

被折叠的 条评论
为什么被折叠?



