基礎資料型別 (Elementary Data Type) 整型,長整型,浮點,複數,字串
變數
無需聲明或定義類型,在需要時賦值即可使用。
函數定義
def 函數名(參數列表)
變數使用無需聲明或定義類型,函數也因此沒有必要定義傳回型別。
預設情況下返回的是None。
函數的注意點
1. 形參是值傳遞
2. 為外部變數賦值,使用global關鍵字
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'Value of x is', x
3. 支援預設參數
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
4. 支援關鍵參數。即指定實參的形參。
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
輸出
>>>
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
>>>
5. pass表示空語句塊
def someFunction():
pass
6. 文檔字串 DocStrings
在函數定義後的第一個邏輯行若是字串,則是這個函數的文檔字串。
即可被調用的說明語句。調用方法為 函數名.__doc__
文檔字串的慣例是:
一個多行字串,它的首行以大寫字母開始,句號結尾。
第二行是空行,
從第三行開始是詳細的描述。
def printMax(x, y):
'''This is DocStrings.
return max number.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__