101 Python基礎 第三章 函式

2021-09-30 11:35:16 字數 1525 閱讀 3413

第三章: 函式

python的元件包括函式,類,模組和包。包是模組的集合,模組是函式和類的識別符號(識別符號指變數和函式名)集合。

命名空間儲存與識別符號及其繫結值有關的資訊,python定義3個空間:區域性(local),全域性/模組(global),內建(built-in)。python按從區域性到全域性到內建的順序在命名空間中查詢識別符號的值,比如每個模組都有__name__表示模組名。但不同命名空間同名的變數可能引起邏輯錯誤。

函式引數的傳值方式:傳值,用拷貝值;傳引用,對原值修改。python

規定「傳物件引用」,是傳值和傳引用的結合,即如引數是可變物件當做傳引用,如引數是不可變物件當做傳值。

如在\python\lib裡面:

import modulename, module2name

modulename.functionname()

匯入模組, 使用方法-模組名.方法名

示例import math

print math.cos(3)

import random

print

random.randrange(1, 7)

from math import sin, cos, tan

from math import *

直接匯入會話的命名空間, 使用方法-直接用(前面不用模組名)

*的話不含以下劃線的的識別符號,不推薦!

import random as randommodule

from math import sqrt as squareroot

建立了乙個叫randommodule的模組引用

建立了乙個叫squareroot的函式引用

defsquare(y):

return y*y

print square(10)

函式的格式:

一定要用冒號:

用縮排表示主體;

返回值:如沒return就返回none值。

defcalvolumn(x=1, y=2, z=3):

return x * y * z

print calvolumn(2)

預設引數

一定要靠右邊排列, 非預設引數放左邊.

defcalvolumn(x=1, y=2, z=3):

return x * y * z

print calvolumn(y=4)

顯式引數(關鍵字):引數的順序隨便。

但是混合顯式和非顯式引數容易導致錯誤。

遞迴:遞迴呼叫(recursivecall),或又稱遞迴步驟(recursivestep)。不過遞迴費時又耗記憶體,但有時直觀易理解。

較靈活的呼叫方法:

options = [ textfile, updaterecord, newrecord, deleterecord ]

options[ number - 1 ]( argument )

把所有的方法名字放到乙個列表中,如果用列表的下標去呼叫函式。

Pytho基礎 第三章

3.1.1 def語句和引數 在呼叫print 或 len 等函式時,會傳入一些值放於括號中間,在此稱為引數。也可以自行定義接收引數的函式。def hello name print hello name hello yang 在此函式定義中,name為乙個 變元 即可以存放引數以及賦值。值得注意的是...

第三章 語言基礎

它是操作符,不是函式,所以不需要引數 也可以使用引數 let message x console.log typeof message string 以下是乙個特殊情況 console.log typeof null object 因為null被認為是乙個對空物件的引用。0.這個型別只有乙個值 un...

Python基礎教程(第三章)

字串格式化 format hello s,s enough for ya format稱為格式化字串 value world hot print format value 模板字串 from string import template s template x,glorious x s.subst...