Python編程:從入門到實踐------第8章:函數

一、定義函數

下面是一個打印問候語的簡單函數。

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

greet()

輸出如下:

Hello!

動手試一試 8-1 — 8-2

#8-1

def display_message():
    """指出你在本章學的是什麼"""
    print("You are learning function.")

display_message()


#8-2

def favorite_book(title):
    """打印一條消息"""
    print("One of my favorite book is "+title+".")

favorite_book("The old man and the sea")

輸出如下:

You are learning function.
One of my favorite book is The old man and the sea.

二、傳遞實參

相關內容與C語言規則相同。

動手試一試 8-3 — 8-5

#8-3

def make_shirt(size,text):
    print("This is a "+size+"—size shirt and have "+"\""+text+"\""+" on it.")

make_shirt('small','B')
make_shirt(size='small',text='B')


#8-4

def make_shirt(size='big',text='I love python'):
    print("This is a " + size + "—size shirt and have " + "\"" + text + "\"" + " on it.")

make_shirt()
make_shirt('small')
make_shirt(text='I hate python')


#8-5

def describe_city(name,country='China'):
    print(name+" is in "+country+".")

describe_city('Beijing')
describe_city('Shanghai')
describe_city('Pairs','Franch')

輸出如下:

This is a small—size shirt and have "B" on it.
This is a small—size shirt and have "B" on it.

This is a big—size shirt and have "I love python" on it.
This is a small—size shirt and have "I love python" on it.
This is a big—size shirt and have "I hate python" on it.

Beijing is in China
Shanghai is in China
Pairs is in Franch

三、返回值

與C語言規則相同。

動手試一試 8-6 — 8-8

#8-6

def city_country(name,country):
    String = name+","+country
    return String

print("\""+city_country('Beijing','China')+"\"")
print("\""+city_country('Shanghai','China')+"\"")
print("\""+city_country('Pairs','Franch')+"\"")


#8-7

def make_album(singer,song):
    album = {}
    album[singer] = song
    return album

Album = make_album('Eason','Happy cloudy day')
print(Album)


#8-8

while True:
    singer = input("Please input a singer:")
    song = input("Please input one of his/her song:")
    Album = make_album(singer,song)
    print(Album)

    judge = input("Do you want to repeat?(y/n)")
    if judge == 'y':
        continue
    elif judge == 'n':
        break

輸出如下:

"Beijing,China"
"Shanghai,China"
"Pairs,Franch"

{'Eason': 'Happy cloudy day'}

Please input a singer:zhangsan
Please input one of his/her song:a
{'zhangsan': 'a'}
Do you want to repeat?(y/n)y
Please input a singer:lisi
Please input one of his/her song:b
{'lisi': 'b'}
Do you want to repeat?(y/n)n

4.傳遞列表

python支持在函數中傳遞列表,並對列表進行修改等操作。

若要禁止函數修改列表,可創建列表的副本,爲列表名+[:]
例如user_name[:]。

動手試一試8-9 — 8-11

#8-9

def show_magicians(magicians):
    for magician in magicians:
        print(magician)

Magicians = ['a','b','c']
show_magicians(Magicians)


#8-10

def make_great(magicians,great_magicians):
    while magicians:
        magician = magicians.pop()
        modified_magician = "the Great "+magician
        great_magicians.append(modified_magician)

Magicians = ['a','b','c']
Great_magicians = []
#make_great(Magicians,Great_magicians)
#show_magicians(Great_magicians)


#8-11

make_great(Magicians[:],Great_magicians)
show_magicians(Magicians)
show_magicians(Great_magicians)

輸出如下:

a
b
c
a
b
c
the Great c
the Great b
the Great a

5.傳遞任意數量的實參

1. 只設置任意數量的實參

def make_pizza(*toppings):
   ...

此處的toppings爲一個tuple即元組,可接收任意數量的實參.

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

def make_pizza(size,*toppings)

如果要讓函數接受不同類型的實參,必須在函數定義中將接納任意數量實參的形參放在最後。Python先匹配位置實參和關鍵字實參,再將餘下的實參都收集到最後一個形參中。 例如,如果前面的函數還需要一個表示比薩尺寸的實參,必須將該形參放在形參*toppings 的前面.

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

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

動手試一試 8-12 — 8-14

#8-12

print("\n8-12:")
def make_sandwich(*toppings):
    print("\n Make this sandwich with the following toppings:")
    for topping in toppings:
        print("-"+topping)

make_sandwich('mushrooms')
make_sandwich('tomato','potato')
make_sandwich('strawberry','chicken','meat')


#8-13

print("\n8-13:\n")
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

profile = build_profile('mh','wu',
                        age='20',
                        sex='man')
print(profile)


#8-14

print("\n8-14:\n")
def car_messages(manufacturer,model,**messages):
    car = {}
    car['Manufacturer'] = manufacturer
    car['Model'] = model
    for key,value in messages.items():
        car[key] = value
    return car

Car = car_messages('subaru','outback',color = 'blue',tow_package = 'True')
print(Car)

輸出如下:


 Make this sandwich with the following toppings:
-mushrooms

 Make this sandwich with the following toppings:
-tomato
-potato

 Make this sandwich with the following toppings:
-strawberry
-chicken
-meat

8-13:

{'first_name': 'mh', 'last_name': 'wu', 'age': '20', 'sex': 'man'}

8-14:

{'Manufacturer': 'subaru', 'Model': 'outback', 'color': 'blue', 'tow_package': 'True'}

6.將函數存儲在模塊中

函數的優點之一是,使用它們可將代碼塊與主程序分離。通過給函數指定描述性名稱,可讓主程序容易理解得多。你還可以更進一步,將函數存儲在被稱爲模塊 的獨立文件中, 再將模塊導入到主程序中。import 語句允許在當前運行的程序文件中使用模塊中的代碼。

(1)導入整個模塊

寫一個xxx.py文件,再在同一目錄下創建一個.py文件,import xxx即可。

若要應用xxx中的abc()函數,只需通過語句

xxx.abc()

(2)導入特定的函數

若要導入xxx中的函數fun(),只需執行語句

from xxx import fun

(3)使用as給函數指定別名

from pizza import make_pizza as mp

上面的import 語句將函數make_pizza() 重命名爲mp() ;在這個程序中,每當需要調用make_pizza() 時,都可簡寫成mp() ,而Python將運行make_pizza() 中的代 碼,這可避免與這個程序可能包含的函數make_pizza() 混淆。

(4)使用as給模塊指定別名

import pizza as p

p.make_pizza(16,'fish')

上述import 語句給模塊 pizza 指定了別名p,但該模塊中所有函數的名稱都沒變。調用函數make_pizza() 時,可編寫代碼p.make_pizza() 而不是pizza.make_pizza() ,這樣不僅能使代碼更簡潔,還可以讓你不再關注模塊名,而專注於描述性的函數名。這些函數名明確地指出了函數的功能,對理解代碼而言,它們比模塊名更重要。

(5)導入模塊中的所有函數

使用星號(* )運算符可讓Python導入模塊中的所有函數:

from pizza import *

make_pizza(16,'fish')

注意:使用並非自己編寫的大型模塊時,最好不要採用這種導入方法:如果模塊中有函數的名稱與你的項目中使用的名稱相同,可能導致意想不到的結果:Python可能遇到多個名稱相同的函 數或變量,進而覆蓋函數,而不是分別導入所有的函數。

動手試一試 略

發佈了8 篇原創文章 · 獲贊 0 · 訪問量 446
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章