Python学习笔记(八)

来源:互联网 发布:工信部 域名备案 时间 编辑:程序博客网 时间:2024/05/21 06:32

1.函数就是程序中可重复使用的程序段
用关键字“def”来定义,给一段程序起一个名字,用这个名字来执行一段程序,反复使用

# coding:utf-8def say_hi():    print("hi!")say_hi()
#参数Functiondef 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")
#有返回值的functiondef repeat_str(str,times):    repeated_strs = str * times    return repeated_strsrepeated_string = repeat_str("Happy Birthday", 4)print(repeated_string)
#全局变量与局部变量x = 60def fao(x):    print("x is " + str(x))    x = 3    print("change local x to " + str(x))fao(x)print("x is still " + str(x))
#global 用法y = 60def foo():    global y    print("y is " + str(y))    y = 3    print("change local y to " + str(y))foo()print("x is " + str(y))

2.默认参数、关键字参数、VarArgs参数

#默认参数def repeat_str1(str,times=1):    repeated_strs = str * times    return repeated_strsrepeated_string = repeat_str1("Happy Birthday")print(repeated_string)
#关键字参数#f(a,b =2)#合法#f(a =2 ,b)#不合法#关键字参数def func(a,b =4,c =8):    print("a is",a,"b is",b,"c is",c)func(13, 17)func(125,c=26)func(c=28,a=5)
#VarsArgs参数def print_paras(fpara,*nums,**word):    print("fpara:"+str(fpara))    print("nums"+ str(nums))    print("words"+ str(word))print_paras("Hello",1,3,5,7,word = "python", another_word = "java")
原创粉丝点击