1. 程式人生 > >Python學習筆記05-函 數

Python學習筆記05-函 數

定義函式

def greet_user():"""顯示簡單的問候語"""
 print("Hello!")
greet_user()

向函式傳遞資訊

def greet_user(username):
    """ 顯示簡單的問候語 """
    print("Hello, " + username.title() + "!")
    greet_user('jesse')
Hello, Jesse!

傳遞引數

def describe_pet(animal_type, pet_name):
"""顯示寵物的資訊"""
    print("\nI have a "
+ animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".")

關鍵字實參

def describe_pet(animal_type, pet_name):
"""顯示寵物的資訊"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster'
, pet_name='harry')

預設值

def describe_pet(pet_name, animal_type='dog'):
"""顯示寵物的資訊"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

等效的函式呼叫

describe_pet('willie')
describe_pet(pet_name='willie'
)
# 一隻名為Harry的倉鼠 describe_pet('harry', 'hamster') describe_pet(pet_name='harry', animal_type='hamster') describe_pet(animal_type='hamster', pet_name='harry')

返回值

def get_formatted_name(first_name, last_name):
"""返回整潔的姓名"""
 full_name = first_name + ' ' + last_name
 return full_name.title()
 musician = get_formatted_name('jimi', 'hendrix')
print(musician)

讓實參變成可選的

def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整潔的姓名"""
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = 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):
"""返回一個字典,其中包含有關一個人的資訊"""
 person = {'first': first_name, 'last': last_name}
 return person

musician = build_person('jimi', 'hendrix')
print(musician)

結合使用函式和 while 迴圈

def get_formatted_name(first_name, last_name):
"""返回整潔的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()


while True:
    print("\nPlease tell me your name:")
    f_name = input("First name: ")
    l_name = input("Last name: ")

    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")

向函式傳遞列表

def greet_users(names):
"""向列表中的每位使用者都發出簡單的問候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)  

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

禁止函式修改列表

function_name ( list_name [:])
print_models(unprinted_designs[:], completed_models)

傳遞任意數量的實參

*toppings


def make_pizza(*toppings):
"""列印顧客點的所有配料"""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

結合使用位置實參和任意數量實參

def make_pizza(size, *toppings):
"""概述要製作的比薩"""
    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')

使用任意數量的關鍵字實參

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'}

將函式儲存在模組中

匯入整個模組,要讓函式是可匯入的,得先建立模組。模組是副檔名為.py的檔案
pizza.py

def make_pizza(size, *toppings):
"""概述要製作的比薩"""
    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')

這就是一種匯入方法:只需編寫一條 import 語句並在其中指定模組名,就可在程式中使用該
模組中的所有函式

匯入特定的函式

你還可以匯入模組中的特定函式,這種匯入方法的語法如下:

from  module_name import  function_name

from  module_name import  function_0 ,  function_1 ,  function_2


from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

使用 as 給函式指定別名

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

使用 as 給模組指定別名

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

匯入模組中的所有函式

使用星號( * )運算子可讓Python匯入模組中的所有函式:

from pizza import *


make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

編寫函式時,需要牢記幾個細節。應給函式指定描述性名稱,且只在其中使用小寫字母和下
劃線。描述性名稱可幫助你和別人明白程式碼想要做什麼。給模組命名時也應遵循上述約定。
每個函式都應包含簡要地闡述其功能的註釋,該註釋應緊跟在函式定義後面,並採用文件字
符串格式。文件良好的函式讓其他程式設計師只需閱讀文件字串中的描述就能夠使用它:他們完全
可以相信程式碼如描述的那樣執行;只要知道函式的名稱、需要的實參以及返回值的型別,就能在
自己的程式中使用它。