首页 > 开发 > Python > 正文

python 函数的基础知识

2017-07-06 10:41:58  来源:慕课网
概念

程序中可重复使用的程序段,给一段程程序起一个名字,用这个名字来执行一段程序,反复使用 (调用函数)

语法

用关键字 ‘def' 来定义,identifier(参数),参数为list

局部变量 vs 全局变量
#-*- coding: utf-8 -*-#没有参数和返回的函数def say_hi():    print(" hi!") say_hi() say_hi()#有参数,无返回值 def print_sum_two(a, b):     c = a + b     print(c) print_sum_two(3, 6) def hello_some(str):    print("hello " + str + "!") hello_some("China") hello_some("Python")#有参数,有返回值 def repeat_str(str, times):    repeated_strs = str * times    return repeated_strs repeated_strings = repeat_str("Happy Birthday!", 4) print(repeated_strings)#全局变量与局部 变量 x = 60 def foo(x):    print("x is: " + str(x))    x = 3    print("change local x to " + str(x))  foo(x) print('x is still', str(x))
默认参数
def repeat_str(s, times = 1):    repeated_strs = s * times    return repeated_strsrepeated_strings = repeat_str("Happy Birthday!")print(repeated_strings)repeated_strings_2 = repeat_str("Happy Birthday!" , 4)print(repeated_strings_2)
不能在有默认参数后面跟随没有默认参数
#f(a, b =2)合法#f(a = 2, b)非法
关键字参数: 调用函数时,选择性的传入部分参数
def func(a, b = 4, c = 8):    print('a is', a, 'and b is', b, 'and c is', c)func(13, 17)func(125, c = 24)func(c = 40, a = 80)
VarArgs参数
def print_paras(fpara, *nums, **words):    print("fpara: " + str(fpara))    print("nums: " + str(nums))    print("words: " + str(words))print_paras("hello", 1, 3, 5, 7, word = "python", anohter_word = "java")