函数基础知识

1.函数调用

注意函数名称,参数个数,参数数据类型

2.函数定义

def 函数名(参数):

  函数体

  return 返回值

  (函数中也可以直接使用pass,意为什么也不做,目的是让程序能够运行不报错)

python有一点值得注意,返回值可以为多个,例如:

>>> d={'weight':65,'height':173}
>>> def get_weight_and_height(dirc):
         return dirc['weight'],dirc['height']
>>> a,b=get_weight_and_height(d)
>>> a
173
>>> b
65

看上去好像真的返回了两个值,事实上

>>> a=get(d)

>>> r
(65,173)
>>> type(r)

<class 'tuple'>          #原来返回值是一个tuple

3.函数参数

默认参数

默认参数的存在使得我们能够在使用自己构造的函数时,选择调用一个或多个参数:例如

>>> def power(x,n=2):
                m=1
                while n>0:
                    n-=1
                    m*=x
                return m

>>> power(7)
49
>>> power(7,5)
16807

注意:默认参数一定要放在参数列表最后,默认参数必须指向不变对象

可变参数

def 函数名(*参数):

  函数体

  return 返回值

即在参数前加上*号

原文地址:https://www.cnblogs.com/sgawscd/p/10085484.html