您的位置:首页 > 编程语言 > Python开发

python编程 从入门到实践 第八章 函数 及课后题

2017-10-20 19:33 736 查看
#char 8 函数
#定义函数
#第一类:无参数,无返回值类型
def greet_user():
#greet function
print('Hello')

greet_user()
#第二类:加入了一个参数:
def greet_user(username):
#another greet function
print("Hello "+username.title()+" !")
greet_user('jack')

#实参与形参的区别:
#形参:函数完成工作所需要的信息
#实参:传递给函数的信息
#传递实参-位置实参,排序即与其输出有关
def describe_pet(animal_type,pet_name):
print('\n I have a '+animal_type+" .")
print('my '+animal_type+"'s name is "+pet_name.title())

describe_pet('dog','tom')
#关键字实参,即在输入参数的时候加上参数名字
describe_pet(animal_type='dog',pet_name='sarah')
#此时即可调换顺序了
describe_pet(pet_name='jackson',animal_type='pig')

#关于默认值,默认值要放在后一个参数里
def describe_pet(pet_name,animal_type='dog'):
print('\n I have a '+animal_type+" .")
print('my '+animal_type+"'s name is "+pet_name.title())

describe_pet(pet_name='jack')
describe_pet('jack')
#若为该参数提供了实参,则函数会忽视默认值
#8.3返回值
def get_formatted_name(firstname,lastname):
full_name=firstname+" "+lastname
return full_name.title()

a=get_formatted_name('jackson','chan')
print(a)
#让实参变成可选
#即让可选参数放在最后,用其等于空字符串即可,若有需要则加入该参数,若无需要就忽略
def get_formatted_name(firstname,lastname,middlename=''):
if middlename:
full_name=firstname+" "+middlename+' '+lastname
else:
full_name=firstname+" "+lastname
return full_name.title()
a=get_formatted_name('john','lee','hooker')
b=get_formatted_name('jack','chan')
print(a)
print(b)
#返回字典
def build_preson(firstname,lastname):
#接收参数封装到字典中
person={'first':firstname,'last':lastname}
return person
a=build_preson('jimi','hendrix')
print(a)

def build_another_person(firstname,lastname,age=''):
person={'first':firstname,'last':lastname}
if age:
person['age']=age
return person
a=build_another_person('jimi','hendrix',27)
print(a)
#函数和while结合循环
def get_formatted_name(firstname,lastname):
full_name=firstname+" "+lastname
return full_name.title()
while True:
print('\n please tell me your name')
print("(enter 'q' at any time to quit)")

f_name=input('firstname')
if f_name =='q' :
break

l_name=input('lastname')
if l_name=='q':
break
formatted_name=get_formatted_name(f_name,l_name)
print('\n Hello, '+formatted_name+'!')
#传递列表及在函数中修改列表
def greet_users(names):
for name in names:
msg='Hello, '+ name.title()+" !"
print(msg)

username=['harry','ty','margot']

unprinted_design=['iphone case','robot pendant','dodecahedron']
completed_models=[]
while unprinted_design:
current_design=unprinted_design.pop()
print('printing model: '+current_design)
completed_models.append(current_design)
print("\n The following models have been printed: ")
for completed_model in completed_models:
print(completed_model)

#改变列表:
def print_models(unprinted_design,completed_models):
while unprinted_design:
current_design=unprinted_design.pop()
print('printing models'+ current_design)
completed_mod
98ca
els.append(current_design)

def show_completed_models(completed_models):
print('\n the following models have been printed:')
for completed_model in completed_models:
print(completed_model)
print_models(unprinted_design,completed_models)
show_completed_models(completed_models)
#由于采用了pop,会导致原列表被修改,如果不希望修改元列表,可以使用其副本
#既是list[:],这可以保证原列表不会遭到改变而函数结果与原来一致
#8.5传递任意数量的实参
def make_pizza(*toppings):
print(toppings)

make_pizza('mushroom','green been')

def make_pizza(*toppings):
print('\n making a pizza with the following toppings:')
for topping in toppings:
print('-'+topping)

#结合位置参数
def make_pizza(size,*toppings):
print('\n making a '+str(size) +'inch pizza with the following toppings:')
for topping in toppings:
print('-'+topping)
#使用任意数量的关键字实参
#**user_info相当于传入了一个字典
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
#8-6将函数存储在模块中
#即在一个模块中写函数,在另一个模块中调用该模块
#eg:import pizza 还有 Import pizza as p
#或者从特定的模块中导入特定的函数
#from pizza import make_pizza
#也可以用*导入某个模块的整个函数,即是from pizza import *

课后题

# char 8 homework
#8-1
def display_message():
print("this session is learning function")

display_message()
#8-2
def favourite_book(title):
print('one of my favourite books is '+ title.title())

favourite_book('harry potter')
#8-3
def make_shirt(size,logo):
print('the shirt is '+size+" size and print"+logo)
make_shirt('middle','python')
make_shirt(size='middle',logo='python')
#8-4
def make_shirt(size='large',logo='i love python'):
print('the shirt is '+size+" size and print "+logo)
make_shirt()
make_shirt(size='middle')
make_shirt(logo='notebook')
#8-5
def describe_city(city_name,city_country='china'):
print(city_name+" is belong to "+city_country)
describe_city('shanghai')
describe_city('hangzhou')
describe_city('Reykjavik',city_country='Iceland')
#8-6
def city_country(city,country):
full=city+" , "+country
return full
a=city_country('shanghai','china')
print(a)
#8-7
def make_album(singer_name,album_name,songs_number=""):
message={}
message['singer_name']=singer_name
message['album_name']=album_name
if songs_number:
message['songs_number']=songs_number
return message
a=make_album('sudalv',' chunriguang ',20)
print(a)
#8-8
while True:
ablum_message={}
print("\n please input the message of singer's name")
print("(enter 'q' to quit)")
singer_name=input("singer's name")
if singer_name == 'q':
break
album_name=input("ablum's name")
if album_name=='q':
break
songs_number=input('songs_number')
if songs_number=='q':
break
elif songs_number=='':
ablum_message=make_album(singer_name,album_name)
else:
number=songs_number
ablum_message=make_album(singer_name,album_name,number)
print(ablum_message)
#8-9
def show_magicians(magicians):
for magician in magicians:
print(magician.title())
magicians=['jay chou','liu qian','yifu']
show_magicians(magicians)
#8-10
def make_great(magicians):
for index,magician in enumerate(magicians):
magicians[index]='the great'+magician
return magicians
a=make_great(magicians)
show_magicians(magicians)
#8-11
a=make_great(magicians[:])
show_magicians(magicians)
print(a)
#8-12
def making_sandwich(*toppings):
print('your sandwich has following toppings')
for topping in toppings:
print(topping)
making_sandwich('pork','egg')
#8-13
#8-14
def make_car(name,factory,**car_info):
car_mess={}
car_mess['name']=name
car_mess['factory']=factory
for key,value in car_info.items():
car_mess[key]=value
return car_mess
a=make_car=('subaru','outback',color='blue',two_package=True)
print(a)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: