1.函數就是程序中可重複使用的程序段
用關鍵字“def”來定義,給一段程序起一個名字,用這個名字來執行一段程序,反覆使用
# coding:utf-8
def say_hi():
print("hi!")
say_hi()
#參數Function
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")
#有返回值的function
def repeat_str(str,times):
repeated_strs = str * times
return repeated_strs
repeated_string = repeat_str("Happy Birthday", 4)
print(repeated_string)
#全局變量與局部變量
x = 60
def 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 = 60
def 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_strs
repeated_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")