shg104

导航

Python 之 函数基础

函数的定义:

def 函数名(参数列表):     # def 开始, 参数列表: 可选,最后是冒号

      函数体                   # 函数的具体执行代码

      return [expression] # 返回值, 可选

 

示例:

示例1:求和

def sum(num1, num2, num3=3):        # num3为默认参数

      return num1+num2+num3

# 调用:

total = sum(3,5)          # total=11

total = sum(3,5,8)   # total=16

 

示例2:求Fibonacci数列指定范围内的项

def fib(n):

      a,b=0,1

      while b<n:

           print(b, end=' ')   # print函数中指定end 不换行

           a, b = b, a+b

      print() 

# 调用:

f = fib   # 分派

f(100)        # 或fib(100) 输出:1 1 2 3 5 8 13 21 34 55 89

 

示例3:任意参数方式

def fun(*args):    # 接收任意参数函数

      print(args) 

# 调用

fun(1,2,3,'a','b','c')       # 输出:(1, 2, 3, 'a', 'b', 'c')

 

 示例4:遍历输出

def print_list(the_list):

      for each_item in the_list:

           print(each_item, end=' ')         # print函数中指定end 不换行

 # 调用

listexp=['One', 1, 2, 'Two', 'Three', 'Four', 5];

print_list(listexp)  # 输出: One 1 2 Two Three Four 5

posted on 2017-03-30 16:15  shg104  阅读(52)  评论(0)    收藏  举报