【鬼知道我第八章拖了多少天…
第八章 :函数 (很重要的一章)
8.1 定义函数
打印问候语的一个简单函数
8.1.1 向函数传递信息
调用时 无论传入什么样的名字 都会生成相应的输出
8.1.2 实参和形参
形参: 函数完成其工作所需的一项信息
实参: 调用函数是传递给函数的信息
8.1 动手试一试
- 8-1 消息
#8.1动手试一试
#消息
def display_message():
print ("本章学习的是函数。")
display_message()
- 8-2 喜欢的图书
#8.1动手试一试
#喜欢的图书
def favorite_book(title):
print ("One of my favorite book is " + title +".")
favorite_book('Alice in Wonderland')8.2 传递实参
向函数传递实参的方式有很多 可使用位置实参 这要求实参的顺序与形参的顺序相同 ; 也可使用关键字实参 其中每个实参都由变量名和值组成 ; 还可以使用列表和字典
8.2.1 位置实参
当我们调用函数的时候 Python必须将函数调用的每个实参都关联到函数定义中的一个形参
8.2.2 关键字实参
传递给函数的名称-值对
⚠️注意 使用关键字实参时 务必准确地指定函数定义中的形参名
8.2.3 默认值
正解为:
8.2.4 等效的函数调用
8.2.5 避免实参错误
像这样 未指定参数就是错的
8.2 动手试一试
- 8-3 T恤
#8-3 T恤
def make_shirt(size , message):
print ("衣服的尺码是:" + size)
print(message)
make_shirt('middle','yc')
- 8-4 大号T恤
#8-3 T恤
def make_shirt(size , message = 'I love Python!'):
print ("\n衣服的尺码是:" + size.title())
print("在衣服上打印" + message)
make_shirt('large')
make_shirt('middle')
make_shirt('small' , 'yc')- 8-4 城市
def describe_city(city_name , county = 'china'):
print (city_name.title() + " is in " + county.title())
describe_city('bei jing' , 'china')
describe_city('bei jing')
describe_city('reyljavik' , 'iceland')
describe_city('rome' , 'italy')8.3 返回值
函数并非总是直接显示输出 它是可以处理一些数据 并返回一个或一组值 函数返回的值被称为返回值
return( ) 语句 将值返回到调用函数的代码行
8.3.1 返回简单值
8.3.2 让实参变成可选的
注意是设置为 空字符串
8.3.3 返回字典
8.3.4 结合使用函数和while循环
8.3 动手试一试
- 8-6 城市名
#8-6 城市名
def city_country(city_name , country):
print ('"' + city_name.title() + "," + country.title() + '"')
city_country('yy' ,'cc')
- 8-7 专辑
#8-7 专辑
def make_album(singer_name , the_album , number_of_songs = ''):
if number_of_songs:
the_album = {'singer':singer_name , 'album':the_album , 'number':number_of_songs}
else:
the_album = {'singer':singer_name , 'album':the_album }
return the_album
print(make_album('专辑一' , '信息一' , '10'))
print(make_album('专辑二' , '信息二'))
- 8-8 用户的专辑
def make_album(singer_name , the_album , number_of_songs = ''):
the_album = {'singer':singer_name , 'album':the_album}
return the_album
while True:
print ("This is the album's information:")
print ("(enter 'q' at any time to quit)")
singer = input ("Singer name:")
if singer == 'q':
break
album = input ("The album:")
if album == 'q':
break
print(make_album(singer , album))
啊啊啊啊啊啊啊
今天也偷懒了…
8.4 传递列表
版权声明:本文为SeanYi178原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。