Python學習(十)Python 函數


Python 函數

Python 函數

函數:帶名字的代碼塊,用於完成具體工作。

函數:數學解釋 == function()

計算機中函數: 計算機所有語言函數 == subroutine(子程序),procedure(過程)

作用:

  1. 減少重復代碼
  2. 方便修改,更易擴展
  3. 保持代碼一致性

函數格式:

def 函數名(參數列表):

函數體 < br >< br >


函數命名規則:

  1. 函數名必須以下划線或字母開頭,可以包含任意字母、數字或下划線的組合,不能使用任何的標點符號
  2. 函數名是區分大小寫的
  3. 函數名不能使用保留字(系統定義的函數如:print等)

定義函數

打印問候語的簡單函數

def greet_user(): """Display a simple greeting.""" print("Hello, Jesse !") greet_user()
Hello, Jesse !

向函數傳遞信息

def greet_user(username): """Display a simple greeting.""" print("Hello, %s !"%(username.title())) greet_user('jesse')
Hello, Jesse !

形參:代碼塊中定義的參數,如上文中的“username”

實參:調用函數時給函數傳遞的具體信息,如上文中“jesse”


形參和實參之間的關系

默認:實參和形參是一一對應的,定義幾個形參就需要輸入幾個實參,順序要和形參一致。

關鍵字實參傳遞:可指定你要為那個形參傳遞什么參數,如上文可寫成“greet_user(username = 'jesse')”


函數返回值

返回值:函數並非總是直接顯示輸出,相反,它可以處理一些數據,並返回一個或一組值。函數返回的值稱為返回值


返回值的調用方式:return語句將值返回到調用函數的代碼行

注意:

  1. 函數執行過程中只要遇到return語句,就會停止執行並返回結果,也可以理解為return語句代表函數的結束。
  2. 如果未在函數中指定return,那么這個函數的返回值為“None”
  3. return多個對象,解釋器會把多個對象組裝成一個元組作為一個整體結果輸出。

返回簡單函數值

def get_formatted_name(first_name, last_name, middle_name):

"""Return a full name, neatly formatted."""

full_name = "%s %s %s"%(first_name,middle_name,last_name)

return full_name.title()

musician = get_formatted_name('john', 'hooker', 'lee')

print(musician)

結果:

John Lee Hooker
實參變成可選參數

實參變成可選參數,必須賦予可選參數一個默認值

定義middle_name='',當 middle_name 這個實參不存在時使用默認值空。

為了輸出結果整潔,使用if判斷middle_name存在時執行三個傳參的格式,不存在執行兩個傳參的格式

def get_formatted_name(first_name, last_name, middle_name=''):

判斷傳參

"""Return a full name, neatly formatted.""" if middle_name: full_name = "%s %s %s"%(first_name,middle_name,last_name) else: full_name = "%s %s"%(first_name,last_name) return full_name.title()

調用函數並傳參

musician = get_formatted_name('jimi', 'hendrix')
print(musician) musician = get_formatted_name('john', 'hooker', 'lee') print(musician)

結果顯示整潔

Jimi Hendrix John Lee Hooker
返回字典

函數可返回任何類型的值,包括列表和字典等較復雜的數據結構。

def build_person(first_name, last_name, age=''):

"""Return a dictionary of information about a person."""

person = {'first': first_name, 'last': last_name}

#判斷age值是否為空
if age:

person['age'] = age

return person

musician = build_person('jimi', 'hendrix', age=27)

print(musician)

{'first': 'jimi', 'last': 'hendrix', 'age': 27}
結合使用函數和while循環

def get_formatted_name(first_name, last_name, middle_name=''):

"""Return a full name, neatly formatted."""

if middle_name:

full_name = "%s %s %s"%(first_name,middle_name,last_name)

else:

full_name = "%s %s"%(first_name,last_name)

return full_name.title()

while True:

print("\nPlease tell me your name :")

print("(entre 'q' at any time to quit)")

f_name = input("First name :")

if f_name == 'q' :

break

l_name = input("Last name :")

if l_name == 'q' :

break

musician = get_formatted_name(f_name, l_name)

print("Hello, %s !"%(musician))

Please tell me your name : (entre 'q' at any time to quit) First name :eric Last name :matthes Hello, Eric Matthes !
傳遞列表到函數

個性化問候

def greet_users(names):

"""Print a simple greeting to each user in the list."""

for name in names:

msg = "Hello, " + name.title() + "!"

print(msg)

usernames = ['hannah', 'ty', 'margot']

greet_users(usernames)

Hello, Hannah! Hello, Ty! Hello, Margot!
在函數中修改列表

將列表傳遞給函數后,函數可對其進行修改。

函數對列表做的任何修改時永久的,能夠高效的處理大量數據

def print_models(unprinted_designs, completed_models): """ Simulate printing each design, until there are none left. Move each design to completed_models after printing. """ while unprinted_designs: current_design = unprinted_designs.pop() # Simulate creating a 3d print from the design. print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): """Show all the models that were printed.""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models)

執行結果:

Printing model: dodecahedron Printing model: robot pendant Printing model: iphone case The following models have been printed: dodecahedron robot pendant iphone case
禁止函數修改列表

函數傳遞列表的副本可以保留原始列表的內容不變,除非理由充分需要使用列表副本,否則還是要將原始列表傳遞給函數。

創建列表副本需要花時間與內存創建副本,不創建副本可以提高效率,在處理大型列表時尤其重要。

傳遞任意數量的實參

Python允許函數從調用語句中收集任意數量的實參

函數中形參“ *toppings ” ,不論實參傳遞了多少個都會收入囊中

def make_pizza(size, *toppings): """Summarize the pizza we are about to make.""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

執行結果

Making a 16-inch pizza with the following toppings:
- pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese
使用位置實參和任意數量的關鍵字實參

def build_profile(first, last, **user_info):

"""Build a dictionary containing everything we know about a user."""

profile = {}

profile['first_name'] = first

profile['last_name'] = last

for key, value in user_info.items():

profile[key] = value

return profile

user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')

print(user_profile)

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
  • *args:無命名參數
  • **kwargs:有命名參數,例如字典
def f (*args,**kwargs): # pass for i,id in kwargs.items(): print("%s: %s"%(i,id)) print(args) f(1,2,3,[123,4],name='jorbabe',aut='abc')
name: jorbabe
aut: abc (1, 2, 3, [123, 4])

將函數存儲在模塊中

函數的優點:使用函數可以將代碼塊和主程序分離,通過給與函數指定描述性名稱,使主程序更容易理解。

import 語句允許在運行當前文件中使用模塊中的代碼

函數模塊導入

·1、導入整個模塊 同級目錄調用函數模塊。

  • 創建模塊

    模塊是擴展名稱“.py”的文件,包含要導入程序的代碼
    
    如創建包含函數make_pizza()的模塊pizza
    
    編寫模塊:pizza.py
    
    def make_pizza(size, *toppings): """Summarize the pizza we are about to make.""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
  • 調用模塊:making_pizzas.py

    import pizza pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  • 執行結果:

    Making a 16-inch pizza with the following toppings:
    - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese

模塊導入方式,僅需一個import語句,就可將該模塊中所有的函數導入,該導入方式可以在代碼中使用,module_name.function_name()調用任意一個模塊中的函數,如上文中的 pizza.make_pizza(16, 'pepperoni')

·2、導入特定函數

  • 導入方式 from module_name import function_name

    如上文中可使用:
    
    from pizza import make_pizza
    make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

·3、使用as給函數指定別名

  • 導入方式 from module_name import function_name as xxx

    如上文中可使用:
    
    from pizza import make_pizza as mp
    mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')

·4、使用as給模塊指定別名

  • 導入方式 import module_name as xxx

    如上文中可使用:
    
    import pizza as p p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

·5、導入模塊中所有函數

  • 導入方式 from module_name import *

    如上文中可使用:
    
    from pizza import * make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

函數編寫指南

形參的默認值等號兩端不要有空格

def function_name(parameter_0,parameter_1='value')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM