《Python编程:从入门到实践》学习打卡8-函数

函数

定义

def greet():
    """定义问候函数"""
    print('hello')
def greet(name):
    print('hello,' + name.title())
    
greet()
greet(kim)
  1. 定义函数使用关键词def
  2. 函数名后必须加括号以及冒号。括号内指定函数相关信息,没有信息括号也必不可少
  3. 冒号之后缩进,写函数内的代码
  4. 调用函数时用函数名加括号,如有信息,则在括号内显示
  5. 三个双引号是函数的注释文档

课后习题

8-1消息

def display_message():
    print('I learned the definition of function')
    
# display_message()

8-2喜欢的图书

def favorite_book(title):
    print('one of my favorite books is ' + title.title())
# favorite_book(little prince)

传递实参

位置实参

即实参的位置与形参的位置一一对应,可以同时多次调用

def pet(pet_type,pet_name):
    print('this ' + pet_type + '\'s name is ' + pet_name)
    
pet('labrador','kiki')
pet('domentic','black')

关键字实参

在函数括号内直接将实参与形参进行关联

def pet(pet_type,pet_name):
    print('this ' + pet_type + '\'s name is ' + pet_name)
    
pet(pet_type='labrador',pet_name='kiki') # 形参和实参直接关联
pet('domentic','black')

指定默认值,即直接在函数形参那里指明默认值,此时实参传进去一个值即可,当有默认值时应该将其放在参数表后面,因为python无论设定默认值与否,都会按照位置实参来处理可以对默认值进行修改,只要在对应位置输入修改的值即可。

def pet(pet_type='labrador',pet_name):
    print('this ' + pet_type + '\'s name is ' + pet_name)
pet('kiki') # 编译不过,因为系统会按照位置实参来处理,实参与默认值冲突,应将默认值放在参数表后面

课后习题

8-3消息

def make_shirt(size,printed):
    print('This T-shirt \'s size is ' + str(size) + ' and ' + printed + ' printrd on it')
	# 注意数值和字符串必须统一,使用str将数值转为字符串
make_shirt(32,'hello')

8-4大号T恤

def make_shirt(size,printed='I Love Python'):
    print('This T-shirt \'s size is ' + size + ' and ' + printed + ' printrd on it')

make_shirt('large') # 大号T恤
make_shirt('medium') # 中号T恤
make_shirt('small','hello world') #其他字样T恤

8-5城市

def describe_city(name,nation='china'):
    print(name + ' is in ' + nation)

describe_city('shanghai')
describe_city('seoul','korea')
describe_city('nanjing')

返回值

函数并不总是直接打印结果,经常是对输入进行处理,得到相应的值,该值就是函数的返回值,返回值可以是任何类型,包括列表,字典等,使用return关键词对返回值进行处理

def get_formatted_name(first_name,last_name):;
    full_name = first_name + ' ' + last_name
    return full_name.title() # 对函数返回值可以进一步处理

person = get_formatted_name('kobe','brayant') #将返回值存储在变量中
print(person) # Kobe Brayant

返回字典

在函数内将字典表示出来,将字典整体赋给一个变量,返回变量值即可

def get_formatted_name(first_name,last_name,age=''): # 设立待选值age为空
    if age: # 如果age内不为空,就打印age
        person={'first':first_name,'last':last_name,'age':age}
    else:
        person = {'first':first_name,'last':last_name}
    return person

info = get_formatted_name('kobe','brayant',30)
print(info)

函数与while循环结合

def get_formatted_name(first_name,last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()

while True:
    f_name = input('input your first name(press quit to end program):')
    if f_name == 'quit':
        break
    l_name = input('input your last name:') # 输入用户首尾姓名
    person = get_formatted_name(f_name,l_name) # 代入函数
    print('hello ' + person)

涉及中间名版本

def get_formatted_name(first_name,last_name,middle=''):
    if middle:
        full_name = first_name + ' ' + middle + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()

while True:
    f_name = input('input your first name(press quit to end program):')
    if f_name == 'quit':
        break
    l_name = input('input your last name:')
    m_name = input('input your middle name(no middle name with pressing enter):')
    person = get_formatted_name(f_name,l_name,m_name)
    print('hello ' + person)

课后习题

8-6城市名

def city_country(name,nation):
    info = name + ',' + ' ' + nation
    return info.title()

line = city_country('shanghai','china')
print(line) # Shanghai, China

8-7专辑

def make_album(singer,album,num=''):
    if num:
        line = {'singer':singer,'album':album,'num':num}
    else:
        line = {'singer':singer,'album':album}
    return line

singer1 = make_album('chou','sunshine',5)
print(singer1)
singer2 = make_album('leessang','bicycle')
print(singer2)

8-8用户的专辑

def make_album(singer,album,num=''):
    if num:
        line = {'singer':singer,'album':album,'num':num}
    else:
        line = {'singer':singer,'album':album}
    return line

while True:
    singer_name = input('input singer name(enter quit to end program):')
    if singer_name == 'quit':
        break
    album_name = input('input album name:')
    songs_number = input('input songs number(no with pressing enter):')
    albums = make_album(singer_name,album_name,songs_number)
    print(albums)

传递列表

将列表当作一个参数传递进函数,在函数内可以和往常一样对列表进行处理

def guest(names): # 始终记住传递进来的参数是列表,这一点很重要
    for name in names:
        print('hello ' + name)
guests = ['john','jessi','kathy']
guest(guests)

结合之前将一个列表的值移动到另一个列表中,先使用之前的方法实现,再使用函数实现一次

unprinted_items = ['case','tiger','ball']
completed_items = [] # 已完成列表
while unprinted-items:
    printed_item = unprinted_items.pop() 
    completed_items.append(printed_item) # 已经打印的物件放进已完成列表
for completed_item in completed_items: #遍历已完成列表
    print(completed_item)

函数实现思路:先完成列表的转移,后完成转移后的列表的打印

针对较为复杂的过程,可以将过程分为多步,逐步完成

def move_items(unprinted_items,completed_items):
    while unprinted_items: 
    	temp = unprinted_items.pop()
    	completed_items.append(temp) #完成列表的转移
    
def moved_items(completed_items):
    for completed_item in completed_items:
        print(completed_item) #打印转移后的列表
        
unprinted_items = ['case','tiger','ball']
completed_items= []
move_items(unprinted_items,completed_items) # 此处可以在第一个参数后加[:]创建副本,防止原列表消失
print('following are printed:')
moved_items(completed_items) # 打印转移后的列表

课后习题

8-9魔术师

def show_magicians(magicians):
    for magician in magicians:
        print(magician)
magician = ['john','jessi','kathy']
show_magicians(magician)

8-10了不起的魔术师

def show_magicians(magicians):
    for magician in magicians:
        print(magician)
def make_great(magicians):
    i = 0
    while i < len(magicians): # 循环对每一个值进行修改
        magicians[i] = 'the Great ' + magicians[i]
        i = i + 1
magicians = ['john','jessi','kathy']
show_magicians(magicians)
make_great(magicians) # 改变列表,可对比上下两行列表的结果
show_magicians(magicians)

8-11不变的魔术师

def show_magicians(magicians):
    for magician in magicians:
        print(magician)
def make_great(magicians):
    i = 0
    while i < len(magicians):
        magicians[i] = 'the Great ' + magicians[i]
        i = i + 1
    return magicians
magicians = ['john','jessi','kathy']
imagicians_1 = make_great(magicians[:]) # 存储用副本修改的列表
show_magicians(imagicians_1)
show_magicians(magicians)

传递任意数量的形参

一些情况下我们并不知道函数需要接受多少实参,在python中有一种方法允许接受任意数量的形参,需要在形参前加一个星号(*),此时python会创建一个空元组,将收到的实参都装进元组内。

当参数表既含有位置形参,也含有包含任意数量的形参,应该将位置形参放在前面,包含任意数量的形参放在后面,调用时先输入位置实参,后输入其他实参

def make_pizza(*toppings): # 创建空元组
    print('here is the toppings:')
    for topping in toppings:
        print(topping)
make_pizza('onion','sheese','peppers')
def make_pizza(size,*toppings): # 添加位置形参
    print('you ordered a ' + str(size) + ' inch pizza') # 注意size是数值型,要改为字符串
    print('here is the toppings:')
    for topping in toppings:
        print(topping)
make_pizza(12,'onion','sheese','peppers')

最后一种是使用任意数量的关键词实参,即我们不知道会给函数传递什么样的值,此时,将函数编写成能够接受任意键值对的形式,用户输入多少信息,就接受多少信息,两个星号代表一个字典,多余的信息传进一个字典

def build_info(first_name,last_name,**user_info):
    profile = {} # 创建一个空字典,接受实参
    profile['first'] = first_name
    profile['last_name'] = last_name
    for key,value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_info('bob','allen',filed='physican') # 键相当于一个变量,这里是给变量赋值
print(user_profile)

课后习题

8-12三明治

def menus(*foods):
    print('foods in sandwich are:')
    for food in foods:
        print(food)
menus('onion','beef','cheese')

8-13用户简介

def build_info(first_name,last_name,**user_info):
    profile = {} # 创建一个空字典,接受实参
    profile['first'] = first_name
    profile['last_name'] = last_name
    for key,value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_info('kobe','brayant',filed='basketball',nation='American',champions='5')
print(user_profile)

8-14汽车

def car_info(manufacture,_type,**other_info):
    info = {}
    info['manufacture'] = manufacture
    info['type'] = _type
    for key,value in other_info.items():
        info[key] = value
    return info

show_car = car_info('honda','business',color='red',two_package=True)
print(show_car)

函数存储在模块中

将函数存储在一个模块中,可以方便后续的直接使用以及与他人的分享,使用import语句可将存储在程序文件中的模块导出并直接加以使用

例如上文课后习题8-14,可以将其封装成一个模块,其拓展名为car.py,在该模块目录下再次创建一个后缀名为py的文件,当在该文件想调用car_info函数,只需输入import car即可,然后输入参数即可求出结果

import car
show_car = car_info('honda','business',color='red',two_package=True)
print(show_car)

模块不一定只含有一个函数,它可以包含很多函数,我们可以导入一部分函,也可以导入所有函数

from module_name import function_name # 导入指定函数
from module_name import func1,func2,func3 #导入部分函数
from module_name import * # 星号代表导入模块中所有函数,由于可能存在变量名一致,一般不要这么做

当导入的函数与现有的函数名称相互冲突,或者模块名与现有变量冲突,还可以为导入的函数和模块改变名称

from car import car_info as c_i
import car as qiche

函数编写要点

  1. 函数名及变量名应该带有描述性质,使用小写字母加下划线组合进行命名,这有利于阅读代码
  2. 在函数部分加上三个双引号进行相应的注释,阐述函数的作用,参数含义等

课后习题

8-15打印模型

def print_models(unprinted_models,completed_models): #将该函数单独放在printing_functions文件
    while unprinted_models:
        temp = unprinted_models.pop()
        completed_models.append(temp)
def printed_models(completed_models):
    for completed_model in completed_models:
        print(completed_model)

import printing_functions # 导入模块
unprinted_models = ['case','tiger','hat']
completed_models = []
print('following are printing:')
print_x = printing_functions.print_models(unprinted_models,completed_models) # 注意函数的调用形式,要在前面加模块名
print(print_x)
print('following are printed:')
printed_models(completed_models)

8-16导入

import printing_functions
from printing_funtions import print_models
from printing_funtions import print_models as pm
import printing_funtions as pm
from printing_funtions import *
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值