《Python編程:從入門到實踐》知識點 第8章 函數

《Python編程:從入門到實踐》知識點 第2-4章

《Python編程:從入門到實踐》知識點 第5-7章

第8章 函數

定義函數 傳遞實參

在這裏插入圖片描述

def pet(name, aniaml_type = 'dog'):
    """寵物的信息"""
    print("\nMy " + aniaml_type + "'s name is " + name + ".")

pet('jack')
pet(name='jack')

pet('harry', 'hamster')
pet(aniaml_type='hamster', name='harry')
pet(name='harry', aniaml_type='hamster')
#運行結果
My dog's name is jack.

My dog's name is jack.

My hamster's name is harry.

My hamster's name is harry.

My hamster's name is harry.

返回值

def person(name, age = ''):
    """人的信息,返回一個字典"""
    person = {'name': name}
    if age:
        person['age']= age
    return person

musician = person('jimi')
player = person('lucy', age=21)
print(musician)
print(player)
#運行結果
{'name': 'jimi'}
{'name': 'lucy', 'age': 21}

傳遞任意數量的實參

#形參名*toppings創建一個空元組,將所有值都裝到這個元組裏
def make_pizza(size, *toppings):
    """概述要製作的披薩"""
    print("\n Making a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')
#運行結果
 Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
#形參名*toppings創建一個空元組,將所有值都裝到這個元組裏
def build_profile(first,last, **user_info):
    """創建一個字典,包含用戶的各種信息"""
    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'}

將函數存在模塊中

#導入模塊
import pizza
pizza.make_pizza(16,'mushrooms')

#導入模塊的特定函數
from pizza import make_pizza
make_pizza(16,'mushrooms')

在這裏插入圖片描述

#導入模塊
import pizza as p
p.make_pizza(16,'mushrooms')

#導入模塊的特定函數
from pizza import make_pizza as mp
mp(16,'mushrooms')

在這裏插入圖片描述

from pizza import *
pizza.make_pizza(16,'mushrooms')

函數編寫指南

在這裏插入圖片描述

def function_name(
        para0,para1,para2,
        para3,para4,para5):
    function body...

《Python編程:從入門到實踐》知識點 第9章 類

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章