python编程从入门到实践第八章习题

    python编程从第八章开始开始指数般地变难了,当然也和作者排版有些关系,在前面不把每一章的难点放出来,而在后面穿插着把前面的难点一起丢出来了。

    第八章介绍的函数基本的格式:

def function(objecth):
	pass

和C相比,只是多了def一词,并且返回的数据不需要事先定义类型,可以说还是很简便的。

    python的参数匹配分为两种,一种是位置匹配,另一种是关键词匹配,两种也可以混合使用,但是混合使用容易出现混乱,所以并不建议。这个是完全凭借个人对它的熟悉程度去使用的,但是还是建议在小程序中使用位置匹配,在大程序或者参数较多的时候使用关键词匹配。

    在python3中,传入形参的必须是字符串,所以如果需要传入数字,需要在函数将字符串转化位相应格式的数字。

    在传入列表的时候,如果不加[:],则传入的是列表的本身,而非副本,在列表最后加入[:]则传入的是列表的副本。

    如果传入多个相同类型的参数,可以在形参前面加个*,表示可以接受任意个形参(至少一个),但是如果还需要传入其他参数,则需要放在有*的前面,并且一个参数列只能最多有一个*。


    导入模块
    和C一样,python也可以导入模块,只是语句为:
   
import os
import pizza as pz
from pizza import func1,func2
from os import *

上面四种为导入的四种基本方式,基本只要看到了就不会记错的,也就不多解释了。

好了,下面开始上题目:





#8-1
def display_message():
	print("in this paragraph, we learn function")

display_message()

#8-2
def favorite_book(title):
	print("one of my favorite book is " + title.title())

fbook = "alice in wonderland"
favorite_book(fbook)

#8-3
def make_shirt(size,show_words):
	print("The shirt is "+size+" size"+" and there is "+show_words+"on it")

make_shirt('2','I love')
make_shirt(size='4',show_words="Love")#必须传入的是字符串

#8-4
def make_shirt(size='big',show_words='I love Python'):
	print("The shirt is "+size+" size"+" and there is "+show_words+"on it")

make_shirt()
make_shirt('middle')
make_shirt(show_words='I hate it ')

#8-5
def describe_city(city,country='Iceland'):
	print(city+" is in "+country)

describe_city("Beijing","China")
describe_city("Reykjavik")
describe_city("NewYork",'USA')

#8-6
def city_country(city,country):
	lists=city+","+country
	return lists
print(city_country("Beijing","China"))
print(city_country("NewYork","USA"))
print(city_country("Reykjavik","Iceland"))

#8-9
def show_magicians(magicians):
	for magician in magicians:
		print(magician)

magicians = ['One','Two','Three']
show_magicians(magicians)

#8-10
def make_great(magicians):
	for magician in magicians:
		new_magician = "the great "+ magician
		magicians[magicians.index(magician)] = new_magician
make_great(magicians)
show_magicians(magicians)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值