Python函數中的變數和函數傳回值

來源:互聯網
上載者:User

標籤:coding   port   內部使用   one   tin   pid   cts   file   auth   

1.函數的變數

局部變數和全域變數:

Python中的任何變數都有特定的範圍

在函數中定義的變數一般只能在該函數內部使用,這些只能在程式的特定部分使用的變數我們稱之為局部變數

在一個檔案頂部定義的變數可以供檔案中的任何函數調用,這些可以為整個程式所使用的變數稱為全域變數。

    def fun():

        x=100

        print x

    fun()

    x = 100

    

    def fun():

        global x   //聲明

        x +=1

        print x

    fun()

    print x


外部變數被改:

    x = 100

    def fun():

        global x   //聲明

        x +=1

        print x

    fun()

    print x


內部變數外部也可用:

    x = 100

    def fun():

        global x

        x +=1

       global y

        y = 1

        print x

    fun()

    print x

    print y

    x = 100

    def fun():

        x = 1

        y = 1

        print locals()

    fun()

    print locals()

    {'y': 1, 'x': 1}

    統計程式中的變數,返回的是個字典

    {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:/PycharmProjects/untitled/python/2018.01.03/bianliang.py', '__package__': None, 'x': 100, 'fun': <function fun at 0x02716830>, '__name__': '__main__', '__doc__': None}

    

2. 函數的傳回值

函數傳回值:

函數被調用後會返回一個指定的值

函數調用後預設返回None

return傳回值

傳回值可騍任意類型

return執行後,函數終止

return與print區別

    def fun():

        print 'hello world'

          return 'ok'

        print 123

    print fun()

    hello world

    123

    None


    #/usr/bin/env python

    # -*- coding:utf-8 -*-

    # @time   :2018/1/2 21:06

    # @Author :FengXiaoqing

    # @file   :printPID.py

    import sys

    import os

    def isNum(s):

        for i in s:

            if i not  in '0123456789':

        return False

        return True

    for i in os.listdir("/proc"):

        if isNum(i):

    print i

    

    import sys

    import os

    def isNum(s):

        if s.isdigit():

            return True

        return False

    for i in os.listdir("/proc"):

        if isNum(i):

           print i

或:

    #/usr/bin/env python

    # -*- coding:utf-8 -*-

    # @time   :2018/1/2 21:06

    # @Author :FengXiaoqing

    # @file   :printPID.py

    import sys

    import os

    def isNum(s):

        if s.isdigit():

            return True

        else:

            return False

    for i in os.listdir("/proc"):

        if isNum(i):

           print i

習題

1. 設計一個程式,從終端接收10個數字,並使用自己編寫的排序函數,對10個數字排序後輸出.

2. 設計一個函數,接收一個英文單詞,從檔案中查詢該單詞的漢語意思並返回.

    

Python函數中的變數和函數傳回值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.