Python 程式設計入門/Python 程式設計 - 函式
外觀
Python 中的函式是一組程式碼,執行單個實用程式,可能或可能不返回結果。函式提供了將複雜程式碼分解為可重用程式碼塊的方法,這些程式碼塊可以用作不同程式的構建塊。Python 已經提供了許多內建函式,例如 print、input 等。您可以編寫自己的 Python 函式,稱為使用者定義函式。
如前所述,可以編寫一組程式碼來執行某些實用程式。以下規則提供了編寫自己的函式的指南。當用戶定義的函式名稱呼叫函式時,函式將被執行。
函式塊以關鍵字“def”開頭,後跟使用者提供的函式名稱和括號 ()。使用者提供給函式的輸入放在括號內,進一步擴充套件括號可用於定義要在使用者定義函式內使用的新的引數。Python 提供文件,可用於描述函式、作者、建立日期和使用者定義函式的目的等。可以使用使用者定義函式名稱後的 __doc__ 關鍵字訪問使用者定義函式的文件。關鍵字 return 用於退出函式,可選地將表示式傳遞給函式的呼叫者。
def functionname(parameters): ‘’’function docstring’’’
程式碼塊
Return(expression)
例子
>>> def squareofnum(n):
This function returns the square of the number passed as the parameter
return n*n
>>> print squareofnum(3)
9
>>> print squareofnum.__doc__
This function returns the square of the number passed as the parameter
>>>
>>> def myappendlist(mylist,a):
this function appends a list to the already existing list
mylist.append(a)
return
>>> a=[1,2,3,4]
>>> b=[6]
>>>
>>> a
[1, 2, 3, 4]
>>> b
[6]
>>> print myappendlist(a,b)
None
>>> a
[1, 2, 3, 4, [6]]
>>>
可以透過按正確的順序傳遞引數、提及關鍵字引數、預設引數、可變長度引數來呼叫函式。
#function is defined here
>>> def newfunction(n):
print "inside function"
answer= n*n*n
return answer
>>> print newfunction(2)
inside function
8
>>> print newfunction()
Traceback (most recent call last):
File "<pyshell#203>", line 1, in <module>
print newfunction()
TypeError: newfunction() takes exactly 1 argument (0 given)
>>>
>>> def vistingcard(name, age="22"):
print "the name is %s" %name
print "the age is %d" %age
return
>>> vistingcard("new", 33)
the name is new
the age is 33
>>> vistingcard(age=34, name="no name")
the name is no name
the age is 34
>>> vistingcard(36, "newname")
the name is 36
Traceback (most recent call last):
File "<pyshell#221>", line 1, in <module>
vistingcard(36, "newname")
File "<pyshell#218>", line 3, in vistingcard
print "the age is %d" %age
TypeError: %d format: a number is required, not str
>>>
可以使用 * 將可變長度引數傳遞給函式。以下提供了示例。
>>> def variableargfunc(*argu):
print "inside function"
for a in argu:
print a
return
>>> variableargfunc(10)
inside function
10
>>>
>>> variableargfunc(10,20)
inside function
10
20
>>>
>>> variableargfunc([1,2,3,4,5])
inside function
[1, 2, 3, 4, 5]
在使用它們的函式的作用域內定義了兩種型別的變數。函式內的變數對函式是區域性的,被稱為函式的區域性變數,全域性變數是在變數作用域之外定義的。
>>> globalvariable=0
>>> def scopefunc(n,m):
globalvariable=n+m
print "the local variable is %d " %globalvariable
return globalvariable
>>>
>>> print "outside the function scope %d " %globalvariable
outside the function scope 0
>>> scopefunc(5,6)
the local variable is 11
11
>>> print "outside the function scope %d " %globalvariable
outside the function scope 0
>>>