重讀LPTHW-Lesson18-21 函數

1.def 定義函數,選取合適的函數名,原則是易於理解、閱讀。函數名格式與變量命名格式相同,以字母開始,能夠包含字母、數字、下劃線。函數命名後,把參數放在()中,能夠無參數。而後:結束函數命名,開始函數主體部分。主體部分開頭縮進4個空格。函數

# -*- coding: utf-8 -*-
def print_input(user_input):
    user_input = raw_input("請輸入需打印的內容".decode('utf-8').encode('gbk'))
    print user_input
        

2.能夠在定義函數時指定某個/些參數的默認值:spa

def exponential(bottom,exponent = 2):
    value = bottom ** exponent
    print "%d ** %d = %d" % (bottom,exponent,value)
exponential(20)
exponential(20,3)

輸出:3d

PS:只有在末尾的參數能夠定義默認參數值。def func(a,b = 5)有效;而def func(a = 5,b)無效code

3.使用global 來聲明全局變量。注意全局變量和局部變量的區別blog

(1)局部變量的例子:utf-8

def func(x):
    print "x is ",x
    x = 2
    print "Change local x to",x
x = 50
func(x) print "x is still",x

輸出:input

(2)聲明全局變量:class

def func():
    global x
    
    print "x is",x
    x = 2 
    print "Change local x to",x

x = 50
func()
print "Now value of x is",x

輸出:變量

4.在調用函數而爲參數賦值時,能夠使用關鍵參數法。即調用的函數有多個參數,只想指定其中一部分則能夠經過命名來爲這些參數賦值,這樣的優勢有:①不用擔憂參數賦值的順序②假設其餘參數有默認值的話,能夠只給部分參數賦值。coding

eg:

def func(a,b = 5,c = 10):
    print "a is",a,"and b is",b,"and c is",c
func(23,c=34)        #23賦值給a,b用默認值,c賦值34
func(c=2,a = 1)      #c賦值2,a賦值1,b默認值5
func(12,23)          #a賦值12,b賦值23,c默認值10

輸出:

相關文章
相關標籤/搜索