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