Python Learning Note Day 05
今天是Python学习第五天,主要学习内容是:while处理列表、while与input的结合,然后是整个第八章函数的内容。
在学到函数时,发现在函数中改变list,原list也跟着改变,而改变传入的变量时,原变量不会变。这样看起来,对于变量似乎是传值,而对于list就好像是传引用。
深入了解后发现,和其他语言不一样,在Python中,一切皆对象, Python参数传递采用的都是“传对象引用”的方式。
实际上,这种方式相当于传值和传引用的一种综合。如果函数收到的是一个可变对象(比如字典或者列表)的引用,就能修改对象的原始值,相当于通过“传引用”来传递对象。如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象,相当于通过“传值’来传递对象,此时如果想改变这些变量的值,可以将这些用global变量申明为全局变量。
这一点跟PHP完全不同,所以在这里记录下来。
大纲
相关练习代码
# 在列表之间移动元素 new_users=['alice','tom','lisa','lemon'] comfirmed_users=[] while new_users: add_user=new_users.pop() print('Added '+add_user.title()+' to list') comfirmed_users.append(add_user) for item in comfirmed_users: print(item) # 删除列表中多个重复的值 # 例如删除下面animals中的cat,如果要全部删除很不容易,这里可以用while animals=['cat','dog','chicken','cat','bird','cat','fish'] print(animals) animals.remove('cat') print(animals) while 'cat' in animals: animals.remove('cat') print(animals) # 使用用户输入来填充字典 # 例如,模拟一个简单的用户调查 active=True responses={} while active: name=input('What\'your name: ') age=int(input('How old are you ?')) status=input('Anyone else ?(yes/no)') responses[name]=age if status.lower()=='no': active=False for name,age in responses.items(): print('name:'+name) print('age:'+str(age))
# 7-8 熟食店:创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名 # 字;再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders,对于 # 其中的每种三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表 # finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。 sandwich_orders=['Big Mac','Filet-o-Fish','McChicken','Chicken McNuggets'] finished_sandwiches=[] while sandwich_orders: current_sandwich=sandwich_orders.pop() print('I made your '+current_sandwich) finished_sandwiches.append(current_sandwich) # print(sandwich_orders) # 检查是否全部转移完成 for sandwich in finished_sandwiches: print(sandwich) # 7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习7-8 而创建的列表 # sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样 # 的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将 # 列表sandwich_orders 中的'pastrami'都删除。确认最终的列表finished_sandwiches 中 # 不包含'pastrami'。 sandwich_orders=[ 'Big Mac', 'pastrami', 'Filet-o-Fish', 'McChicken', 'pastrami', 'Chicken McNuggets', 'pastrami', ] finished_sandwiches=[] print(sandwich_orders) print('Pastrami has been sold out') while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') while sandwich_orders: current_sandwich=sandwich_orders.pop() print('I made your '+current_sandwich) finished_sandwiches.append(current_sandwich) print(sandwich_orders) for sandwich in finished_sandwiches: print(sandwich) # 7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If # you could visit one place in the world, where would you go?”的提示, # 并编写一个打印调查结果的代码块。 research={} active=True while active: name=input('What\' your name ? ') ans=input('If you could visit one place in the world, where would you go?') research[name]=ans quit=input('Any else ?(yes/no)') if quit=='no': active=False for name,ans in research.items(): print(name+':'+ans)
# 定义函数 # 例子 定义一个简单的打招呼的函数 def say_hello(): """简单打招呼的函数""" print('Hello Python') say_hello() # 改进版,可以给名字打印 def say_hello_1(username): print('Hello '+username.title()) say_hello_1('kiwi') # 在函数say_hello_1()的定义中,变量username是一个形参(parameter)——函数完成其工作所需的一项信 # 息。在代码say_hello_1('kiwi')中,值'kiwi'是一个实参(arguments)。实参是调用函数时传递给函数的信 # 息。我们调用函数时,将要让函数使用的信息放在括号内。在say_hello_1('kiwi')中,将实参 # 'kiwi'传递给了函数say_hello_1(),这个值被存储在形参username中。
# 8-1 消息:编写一个名为display_message()的函数,它打印一个句子,指出你在本 # 章学的是什么。调用这个函数,确认显示的消息正确无误。 def dispaly_message(): print('I learned function in this chapter') dispaly_message() # 8-2 喜欢的图书:编写一个名为favorite_book()的函数,其中包含一个名为title # 的形参。这个函数打印一条消息,如One of my favorite books is Alice in Wonderland。 # 调用这个函数,并将一本图书的名称作为实参传递给它。 def favorite_book(title): print('One of my favorite book is '+title.title()) favorite_book('Three Body')
# 位置实参 # 你调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此, # 最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。 def describe_pet(animal_type, pet_name): """显示宠物的信息""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet('hashiqi','Erha') # 这个函数的定义表明,它需要一种动物类型和一个名字。调用describe_pet()时,需 # 要按顺序提供一种动物类型和一个名字。例如,在前面的函数调用中,实参'hashiqi'存储在形 # 参animal_type中,而实参'Erha'存储在形参pet_name中。在函数体内,使用了这两个形 # 参来显示宠物的信息。 # 关键字实参:关键字实参是传递给函数的名称—值对 看栗子 # 还是上面的函数 describe_pet(animal_type='cat',pet_name='Miaomi') describe_pet(pet_name='Miaomiao',animal_type='cat') # 也就是使用了关键字实参就不用在意参数的位置关系 # But 如果关键字实参以以下方式就不行,因为这样操作实际还是位置实参, # 只不过以变量的形式给了一个实参罢了 pet_name='Miaomiaomi' animal_type='cat' describe_pet(pet_name,animal_type) # 默认值, # def describe_pet_2(animal_type='dog',pet_name): # 有默认值的参数不能放在没有默认值的前面,上面的代码会报错 def describe_pet_2(pet_name,animal_type='dog'): """显示宠物的信息""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet_2('Erha') # 以上调用方式都是对的,按自己需求正确使用就OK # 位置实参 关键字实参 默认值
# 8-3 T 恤:编写一个名为make_shirt()的函数,它接受一个尺码以及要印到T 恤上 # 的字样。这个函数应打印一个句子,概要地说明T 恤的尺码和字样。 # 使用位置实参调用这个函数来制作一件T 恤;再使用关键字实参来调用这个函数。 def make_shirt(size,symbol): """打印T恤""" print('This is a: '+size+' T-shirt and print with: '+symbol) make_shirt('XL','PHP is the best language(逃') make_shirt(symbol='Life is too short, I code with Python',size='XXL') # 8-4 大号T 恤:修改函数make_shirt(),使其在默认情况下制作一件印有字样“I love # Python”的大号T 恤。调用这个函数来制作如下T 恤:一件印有默认字样的大号T 恤、 # 一件印有默认字样的中号T 恤和一件印有其他字样的T 恤(尺码无关紧要)。 def make_shirt_2(size='L',symbol='I love Python'): """有默认值的打印T恤""" print('This is a: '+size+' T-shirt and print with: '+symbol) make_shirt_2() make_shirt_2('M') make_shirt_2(symbol='I love FYX') # 8-5 城市:编写一个名为describe_city()的函数,它接受一座城市的名字以及该城 # 市所属的国家。这个函数应打印一个简单的句子,如Reykjavik is in Iceland。给用 # 于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城 # 市不属于默认国家。 def describe_city(city,country='china'): """打印国家城市名""" print(city.title()+' is in '+country.title()) describe_city('mianyang') describe_city(country='japan',city='tokoyo') describe_city('paris','france')
# 返回值 # 返回一个整洁的姓名 def get_formatted_name(first_name,last_name): """返回整洁的姓名""" full_name=first_name+' '+last_name return full_name.title() full_name=get_formatted_name('kiwi','qing') print(full_name) # 让实参变成可选的 # 譬如 中间名 这个是一个可选项 def get_formatted_name_middle(first_name,last_name,middle_name=''): """返回可以输入中间名的整洁姓名""" if middle_name: full_name = first_name +' '+middle_name+' ' + last_name else: full_name=first_name+' '+last_name return full_name.title() full_name=get_formatted_name_middle('wei','qing') print(full_name) full_name=get_formatted_name_middle('wei','qing','feng') print(full_name) # 返回字典 def build_person(fistname,lastname): """返回一个人的姓名的字典""" dict={'First':fistname.title(),'last':lastname.title()} return dict dict=build_person('kiwi','qing') print(dict) def end(): """结束前打印语句""" print('Opps...Byebye') while True: print('Tell me your name (enter q to quit)') fname=input('OK tell me your first name') if fname.lower()=='q': end() break lname=input("OK now tell me the last name") if lname=='q': end() break print('Your full name is '+get_formatted_name(fname,lname))
# 8-6 城市名:编写一个名为city_country()的函数,它接受城市的名称及其所属的 # 国家。这个函数应返回一个格式类似于下面这样的字符串:"Santiago, Chile" # 至少使用三个城市国家对调用这个函数,并打印它返回的值。 def city_country(city,country): """创建城市国家字符串""" string=city.title()+','+country.title() return string print(city_country('Nanchong','china')) print(city_country(country='japan',city='tokoyo')) # 8-7 专辑:编写一个名为make_album()的函数,它创建一个描述音乐专辑的字典。 # 这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函 # 数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑 # 的信息。 # 给函数make_album()添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调 # 用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并 # 至少在一次调用中指定专辑包含的歌曲数。 def make_album(singer,name,num=0): """创建专辑信息""" album={} if num: album['singer']=singer album['name']=name album['number']=num else: album['singer'] = singer album['name'] = name return album album=make_album('jaychou','qilixiang') print(album) album=make_album('xusong','youhebuke',1) print(album) album=make_album('xuwei','Blue Lotus') print(album) # 8-8 用户的专辑:在为完成练习8-7 编写的程序中,编写一个while 循环,让用户 # 输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album(),并 # 将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。 def end(): """结束前打印字符串""" print('Opps...Byebye') while True: print('enter q to quit ') singer=input('Tell me name of singer: ') if singer.lower()=='q': end() break name=input('Tell me name of album: ') if name.lower()=='q': end() break num=input('Number? ') if num == 'q': end() break print(make_album(singer,name,num))
# 传递列表 # 需求:一堆要打印的东西,打印完成以后,存储到打印完成列表,最后返回打印完成列表 # 将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永 # 久性的,这让你能够高效地处理大量的数据。 unprint=['excel','word','ppt','pdf'] printed=[] def do_print(un): """打印并把元素存入新表""" while un: cprint=un.pop() print(cprint) printed.append(cprint) do_print(unprint) print(printed) print(unprint) # 禁止函数修改列表 # 在上述函数中我们在打印完了之后原来的列表就会被修改了(传值和传引用), # 要想原list 不被修改,请使用切片(也就是传递一个副本)来处理,如下: unprint2=['excel','word','ppt','pdf'] do_print(unprint2[:]) print(printed) print(unprint2)
# 8-9 魔术师: 创建一个包含魔术师名字的列表, 并将其传递给一个名为 # show_magicians()的函数,这个函数打印列表中每个魔术师的名字。 magician_list=['Kiwi','Timo','Kungen','tom'] def show_magicians(lists): """打印列表""" for name in lists: print(name.title()) show_magicians(magician_list) # 8-10 了不起的魔术师:在你为完成练习8-9 而编写的程序中,编写一个名为 # make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the # Great”。调用函数show_magicians(),确认魔术师列表确实变了。 def make_great(lists): """给列表中每个元素都加上the Great""" index=0 for name in lists: lists[index]='the Great '+name index+=1 make_great(magician_list) show_magicians(magician_list) # 8-11 不变的魔术师:修改你为完成练习8-10 而编写的程序,在调用函数 # make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后 # 的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians(), # 确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the # Great”的魔术师名字。 def make_great2(lists): """获得一个新的列表""" num=0 for name in lists: lists[num]='the Great '+name num+=1 return lists great_magicians=make_great2(magician_list[:]) show_magicians(magician_list) show_magicians(great_magicians)
# 传递任意数量的实参,实际传递的是一个元组 # 例如不知道要多少配料,这里要求循环打印出用户提供的配料 def print_peiliao(*peiliao): """打印配料(元组)""" print(peiliao) print_peiliao('辣椒','面粉','鸡蛋','芝麻') def print_peiliao(*peiliao): """分别打印配料""" for peil in peiliao: print(peil) print_peiliao('辣椒','面粉','鸡蛋','芝麻') # 结合使用位置实参和任意数量实参 def make_pizza(size,*peiliaos): """任意数量的实参""" print('Someone ordered a '+str(size)+' pizza and need these peiliao:') for peiliao in peiliaos: print('-'+peiliao) make_pizza(23,'辣椒面','胡萝卜','榴莲','芥末') # 使用任意数量的关键字实参 # 创建一个字典,其中包含我们知道的有关用户的一切 def user_profile(fname,lname,**canshu): """收集用户所有信息""" profile={} profile['Firstname']=fname profile['Lastname']=lname for k,v in canshu.items(): profile[k]=v return profile profile=user_profile('Wei','qing',localtion='chengdu',sex='male',age=25) print(profile)
# 8-12 三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个 # 函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点 # 的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。 def order_san(*foods): """打印食材""" print('客户预定了如下食材:') for food in foods: print('-'+food) order_san('红豆','蜂蜜','牛肉') order_san('猪肉','大葱') order_san('猪肉','大葱','蒜苗') # 8-13 用户简介:复制前面的程序user_profile.py,在其中调用build_profile()来 # 创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键值对。 def user_profile(fname,lname,**canshu): """收集用户所有信息""" profile={} profile['Firstname']=fname profile['Lastname']=lname for k,v in canshu.items(): profile[k]=v return profile profile=user_profile('Wei','qing',localtion='chengdu',sex='male',age=25) print(profile) # 8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接 # 受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的 # 信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用: # car = make_car('subaru', 'outback', color='blue', tow_package=True) # 打印返回的字典,确认正确地处理了所有的信息。 def make_car(maker,model,**canshu): """造车""" car_info={} car_info['Maker']=maker.title() car_info['model']=model.title() for k,v in canshu.items(): car_info[k]=v return car_info car_info=make_car('Benz','CL-200',Color='blue',Speed=150,length=5) print(car_info)
# 文件夹里有一个make_car.py的文件,里面只包含了自定义的make_car的函数 # 把文件名作为module名,在文件开头用 import make_car 引入 # 下面要使用到module的时候就用如下方式使用 # module_name.function_name() import module_sample car_info=module_sample.make_car('Benz','CL-200',Color='blue',Speed=150,length=5) print(car_info)
# 你还可以导入模块中的特定函数 # 通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数: # from module_name import function_0, function_1, function_2 # 若使用这种语法,调用函数时就无需使用句点。由于我们在import语句中显式地导入了函数 # make_car(),因此调用它时只需指定其名称。 from module_sample import make_car car=make_car('volvo','s40',speed=1000) print(car)
from module_sample import make_car as mc car=mc('honda','gtr',speed=1000,pailiang='12L') print(car) # car2=make_car('sb','sc',dd=123) # print(car2) # 上面的import语句将函数make_car()重命名为mc();在这个程序中,每当需要调用 # make_car()时,都可简写成mp(),而Python将运行make_car()中的代码,这可避免与这个程序 # 可能包含的函数make_car()混淆。
# 使用as 给模块指定别名 import module_sample as m car=m.make_car('toyota','gtr',speed=1000) print(car)
# 使用星号(*)运算符可让Python导入模块中的所有函数 # 这样就不用写点号 from module_sample import * profile=user_profile('qing','wei',age=25) print(profile) # import语句中的星号让Python将模块pizza中的每个函数都复制到这个程序文件中。由于导入 # 了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。然而,使用并非自己编写的 # 大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相 # 同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而 # 不是分别导入所有的函数。 # 最佳的做法是,要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。这能 # 让代码更清晰,更容易阅读和理解。这里之所以介绍这种导入方法,只是想让你在阅读别人编写 # 的代码时,如果遇到类似于下面的import语句,能够理解它们: # from module_name import *
# 8-15 打印模型:将示例print_models.py 中的函数放在另一个名为printing_ # functions.py 的文件中;在print_models.py 的开头编写一条import 语句,并修改这个文 # 件以使用导入的函数。 import printing_functions as pf unprinted_designs=['people','republic','of','china'] completed_models=[] pf.print_models(unprinted_designs, completed_models) pf.show_completed_models(completed_models) print(unprinted_designs)
# 8-16 导入:选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一 # 个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它: # import module_name # from module_name import function_name # from module_name import function_name as fn # import module_name as mn # from module_name import * # import practice # profile=practice.user_profile('qing','wei',age=10,height=177) # print(profile) # from practice import user_profile # pro=user_profile('qing','wei',sex='male') # print(pro) # from practice import user_profile as up # pro=up('name','name',age=34) # print(pro) # import practice as pr # pro=pr.user_profile('jjj','ccc',weight=89) # print(pro) from practice import * pro=user_profile('gg','mm',city='chengdu') print(pro)
def make_car(maker,model,**canshu): """造车""" car_info={} car_info['Maker']=maker.title() car_info['model']=model.title() for k,v in canshu.items(): car_info[k]=v return car_info def user_profile(fname,lname,**canshu): """收集用户所有信息""" profile={} profile['Firstname']=fname profile['Lastname']=lname for k,v in canshu.items(): profile[k]=v return profile
def user_profile(fname,lname,**canshu): """收集用户所有信息""" profile={} profile['Firstname']=fname profile['Lastname']=lname for k,v in canshu.items(): profile[k]=v return profile
def print_models(unprinted_designs, completed_models): """ Simulate printing each design, until there are none left. Move each design to completed_models after printing. """ while unprinted_designs: current_design = unprinted_designs.pop() # Simulate creating a 3d print from the design. print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): """Show all the models that were printed.""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
今天学的东西还需要消化,多练习
版权声明:
作者:Kiwi
链接:https://www.qingwei.tech/programe-develops/893.html
来源:清渭技术小站
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
共有 0 条评论