01Python基礎_07函數,01python_07函數

來源:互聯網
上載者:User

01Python基礎_07函數,01python_07函數
  1. 定義函數

1 def add(x, y):2     """Add two numbers.

    The two values must be integers or strings"""  #DocStrings3 a = x + y4 return a

  DocStrings:函數的第一個邏輯行的字串是這個函數的文檔字串。注意,DocStrings也適用於模組和類。文檔字串的慣例是一個多行字串,它的首行以大寫字母開始,句號結尾。第二行是空行,從第三行開始是詳細的描述。

  return 返回特定的值,如果省略,返回 None 。

  2. 設定預設參數

  函數定義時可以設定參數預設值:

def quad(x, a=1, b=0, c=0):    return a*x**2 + b*x + cprint quad(2.0)    #省略有預設參數的參數,只給x賦值

out:4.0

print quad(2.0, b=3)    #給有預設參數的參數賦值

 out:10

  3. 接受不定參數
def add(x, *args):    #x後的參數當作一個元組中的元素    total = x    for arg in args:        total += arg    return totalprint add(1, 2, 3, 4)    #可將參數理解成:1, (2, 3, 4)print add(1, 2)

out:10

  3

  還可以使用關鍵詞傳入參數:

def add(x, **kwargs):    #**kwargs相當於一個字典    total = x    for arg, value in kwargs.items():        print "adding ", arg        total += value    return totalprint add(10, y=11, z=12, w=13)    #可以理解成:10, {y:11, z:12, w:13}

out:  adding  y

  adding  z

  adding  w

  46

  4. 傳入元組、字典
def add(x, y):    """Add two numbers"""    a = x + y    return a    z = (2, 3)print add(*z)    #"*"必不可少w = {'x': 2, 'y': 3}print add(**w)    #"**"必不可少
  5. map方法產生序列

  可以通過 map 的方式利用函數來產生序列:

def sqr(x):     return x ** 2a = [2,3,4]print map(sqr, a)

out: [4, 9, 16]

  根據函數參數的多少,map 可以接受多組序列:

def add(x, y):     return x + ya = (2,3,4)b = [10,5,3]print map(add,a,b)

out: [12, 8, 7]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.