python 基礎之第十天

來源:互聯網
上載者:User

標籤:logout   argv   os.path   輸入   int   參數   file   結果   需求   

局部變數與全域變數

局部變數:在函數裡面定義的,只有當函式活動時才生效

全域變數:不在函數裡面的

In [1]: x=10In [2]: def bar():   ...:     x=20   ...:     print x   ...:     In [3]: xOut[3]: 10#####如果一定要改變全域的變數,使用global參數####In [5]: def bar():   ...:     global x   ...:     x = 20In [6]: xOut[6]: 10In [7]: bar()In [8]: xOut[8]: 20

########################################################################

有個需求:x,y 的和,x一直都是10,每次調用都要輸入10,很麻煩,用add10 = partial(add,10)  就只需要輸入一次

from functools import partialdef add(x,y):    return x+yif __name__ == ‘__main__‘:     print add(10,20)     print add(10,40)     print add(10,89)     add10 = partial(add,10)     print add10(50)

結果:

[[email protected] script]# python add10.py
30
50
99
60

################列出所有目錄下的檔案#############

[[email protected] script]# vim lsdir.py          #!/usr/bin/python# coding:utf-8import sysimport osdef lsdir(folder):    contents = os.listdir(folder)    print ‘\033[31;1m%s\033[0m:\n\033[32;1m%s\033[0m\n‘ % (folder,contents)    for item in contents:        full_path = os.path.join(folder,item)        if os.path.isdir(full_path):            lsdir(full_path)if __name__ == ‘__main__‘:    lsdir(sys.argv[1])

效果:

[[email protected] script]# python lsdir.py /home//home/:[‘herry‘, ‘honey‘, ‘11111.txt‘, ‘hosts‘, ‘fush‘, ‘jerry‘, ‘mima‘, ‘demo‘, ‘cesh.txt‘, ‘fush.txt‘, ‘master‘]/home/herry:[‘.bashrc‘, ‘.bash_logout‘, ‘.bash_profile‘]/home/honey:[‘.bashrc‘, ‘.bash_logout‘, ‘.bash_profile‘]/home/fush:[‘.bashrc‘, ‘.bash_logout‘, ‘.bash_profile‘]/home/jerry:[‘.bashrc‘, ‘.bash_logout‘, ‘.bash_profile‘]

############lsdir2.py#################

[[email protected] script]# vim lsdir2.py          #!/usr/bin/pythonimport osimport sysdef lsdir(folder):    for path,dirs,files in os.walk(folder):        print ‘%s:\n%s\n‘ % (path,(dirs+files))if __name__ == ‘__main__‘:    lsdir(sys.argv[1])

 

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.