python學習筆記(六)- 函數

來源:互聯網
上載者:User

標籤:包含   整數   ==   use   python   let   簡單   函數的參數   count()   

1、函數:(方法、功能)

         1.提高代碼的複用性

         2.讓代碼更簡潔、簡化代碼

1)定義一個簡單的函數

def sayHello():     #函數名,定義函數    print("hello")  #函數體#函數不調用是不會被執行的sayHello()  #調用函數

2)函數的參數:形參、實參

def calc(a,b):   #a,b叫形參(形式參數)#位置參數,也叫必填參數    res = a * b    print(‘%s * %s = %s‘ % (a,b,res))calc(7,8)  #調用函數時,傳入實參(實際參數),7傳給a,8傳給b

3)預設值參數

def op_file(filename,content=None): #content是預設值參數,非必填    pass

 

2、局部變數和return

#局部變數(+ return使用)

         函數裡面定義的變數,都是局部變數,只能在函數裡面用,出了函數就不能用了

         #如果在函數外print(變數) 就會報錯

#return的作用

  1.return xxx   #調用完函數之後,返回處理的結果

  2.結束函數,函數遇到return,函數會立即結束

def op_file(file_name,content=None): #檔案名稱、需要寫入的內容(預設None)    f = open(file_name,‘a+‘,encoding=‘utf-8‘)    f.seek(0)    if content:  #如果內容不為空白(寫入)        f.write(content)        f.flush() #重新整理,立即寫入到檔案    else:    #內容為空白(讀)        all_user = f.read()  #局部變數,在函數裡面定義的變數,只能在函數裡面用,出了函數就不能用了        return all_user    #調用完函數之後,返回處理的結果    f.close()#op_file(‘a.txt‘,‘aaaa\nbbbb‘)   #content傳入值,寫入res = op_file(‘a.txt‘)   #content=None,讀檔案,res接收函數的傳回值print(res)

【例】:return結束函數

def num():    for i in range(5):        print(i)        if i==3:            return   #唯寫一個return,表示立即結束函數,相當於break,返回Noneres = num()print(res)

#>>> 0 1 2 None

【例】函數裡面如果沒有return的話,預設返回None,函數裡面return不是必須的,如果要接收函數的返回結果,就使用return,如果不需要函數結果,就不用return

import stringdef check(pwd):    #密碼長度6-7位,必須包含字母和數字    if len(pwd)>5 and len(pwd)<12:        if set(pwd) & set(string.ascii_letters) and set(pwd) & set(string.digits):            print("密碼合法")        else:            print(‘密碼不合法‘)    else:        print(‘密碼長度6-11位‘)res = check(‘123abcd‘)   #函數裡面如果沒有return的話,預設返回Noneprint(res)

 

3、【例】:寫一個 判斷一個數是否是合法的小數 的函數

#需求分析    #定義一個函數    # 1、小數點個數  .count()=1    # 2、按照小數點進行分割 1.98 ->[1, 98]    # 3、正小數:小數點左邊是正數;右邊也是整數 s.87  98.s    # 4、負小數:左邊:小數點左邊以負號開頭,且只有一個負號;右邊是整數 -9.5        #-9.5->[‘-9‘,5],再-9按‘-‘切割成[‘‘,9]def is_float(s):    s = str(s)    if s.count(‘.‘) == 1:        left = s.split(‘.‘)[0]        right = s.split(‘.‘)[1]        if left.isdigit() and right.isdigit():            print("是正小數")            return True        elif left.startswith(‘-‘) and left.split(‘-‘)[1].isdigit() and left.count(‘-‘)==1 and right.isdigit():            print("是負小數")    #左邊以‘-’開頭,且只有一個負號,左邊再按負號切割後的第二個元素是數字;右邊也是數字            return True     #‘-1‘.split(‘-‘) -> [‘‘,‘1‘]    print("不是小數")  #其它情況返回false    return Falseprint(is_float(1.98))print(is_float(-2.98))print(is_float(-1))   #Falseprint(is_float(‘s.98‘))  #Falseprint(is_float(‘1.s98‘))print(is_float(1.0))  #Trueprint(is_float(-.5))  #Trueprint(is_float(‘.98‘))  #False

 

4、常量:就是一個不變的值,一般全部用大寫字母來定義  #比如PORT = 3306 ,比如,檔案名稱FILENAME = ‘a.txt‘

money = 500
def test(consume): return money - consumedef test1(money): return test(money) + moneymoney = test1(money)print(money) >>> 500

 

5、全域變數:

         公用的變數,都可以用的變數

         如果要修改全域變數的話,那要先聲明一下修改的是全域變數

         #少用全域變數:全域變數不安全,所有人都可以修改;全域變數會一直佔著記憶體

 

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.