Python Learning Note Day 04
今天是Python学习第四天,主要学习内容是:字典的使用、遍历和嵌套;input输入的工作原理;while循环简介等。然后在看书的过程中发现文中一处错误,应当是“奇数”编者写成“偶数”,已自行修改该电子书。
大纲
相关练习代码
# 字典的结构是 dictionary{'键名':'键值','键名':'键值'} # 类似于PHP里的关联数组 alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points']) # 添加键-值对 alien_0['x']=5 alien_0['y']=-1 print(alien_0) # 使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时, # 通常都需要先定义一个空字典。 dictionary={} dictionary['item1']='test' # 修改字典 print('Color of alien is '+alien_0['color']) alien_0['color']='yellow' print('Color of alien is '+alien_0['color']+' now') # 让外星人往右边移动 alien_1={'color':'yellow','speed':'mid','x':12,'y':9} print('X: '+str(alien_1['x'])+' and y: '+str(alien_1['y'])) speed_now='fast' if speed_now == 'slow': x_inc=1 elif speed_now == 'mid': x_inc=3 elif speed_now == 'fast': x_inc=5 alien_1['x']=alien_1['x']+x_inc print('Now x: '+str(alien_1['x'])+' and y: '+str(alien_1['y'])) # 删除字典的键-值对,可以用del来删除 dic_del={'test':1,'tests':2} print(dic_del) del dic_del['tests'] print(dic_del) print('------------------------') language={ 'tina':'C', 'emily':'C#', 'Kiwi':'Python', } print("Kiwi's favorite language is "+ language['Kiwi']+ '.' )
# 6-1 人:使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。 # 该字典应包含键first_name、last_name、age 和city。将存储在该字典中的每项信息都 # 打印出来。 person={ 'first_name':'Kiwi', 'last_name':'qing', 'age':25, 'city':'Chengdu', } print('First name:'+person['first_name']) print('Last name: '+person['last_name']) print('Age: '+str(person['age'])) print('City: '+person['city']) print('------1-----') # 6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出5 个人的名字, # 并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储 # 在字典中。打印每个人的名字和喜欢的数字。 favorite_num={ 'Kiwi':7, 'Shine':3, 'Liam':2, 'Emily':1, 'Tina':9, } favorite="'s favorite number is " print('Kiwi'+favorite+str(favorite_num['Kiwi'])) print('Shine'+favorite+str(favorite_num['Shine'])) print('Liam'+favorite+str(favorite_num['Liam'])) print('Emily'+favorite+str(favorite_num['Emily'])) print('Tina'+favorite+str(favorite_num['Tina'])) print('------2-----') # 6-3 词汇表:Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后 # 者称为词汇表。 # 想出你在前面学过的5 个编程词汇,将它们用作词汇表中的键,并将它们的含 # 义作为值存储在词汇表中。 # 以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加 # 上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n) # 插入一个空行,然后在下一行以缩进的方式打印词汇的含义。 cihuibiao={ 'PHP':'超文本预处理器', 'range':'用于生成指定范围内的数字的函数', 'if':'条件判断语句', '元组':'不可变的列表', '字典':'类似php里的数组' } print('PHP:\n\t'+cihuibiao['PHP']) print('range:\n\t'+cihuibiao['range']) print('if:\n\t'+cihuibiao['if']) print('元组:\n\t'+cihuibiao['元组']) print('字典:\n\t'+cihuibiao['字典'])
# 遍历language languages={ 'Tina':'C', 'Emily':'C#', 'Kiwi':'Python', } for key,value in languages.items(): print('\n'+key+':'+value) # print(v) # 让语句更容易理解,可以改成: for name,language in languages.items(): print('\n'+name.title()+':'+language.title()) # 遍历所有的键 # 方法1: for name in languages.keys(): print(name.title()) # 方法keys() # 方法2: for name in languages: print(name) # 在遍历字典的时候,默认会遍历键,但是使用keys()显式的表达更容易理解 # 打印两条消息,指出两位朋友喜欢的语言。 # 我们像前面一样遍历字典中的名字,但在名字为指定朋友的名字时,打印一条消息, # 指出其喜欢的语言: friends=['Kiwi','tina'] for name in languages.keys(): if name in friends: print('Hello '+name+',your language is '+languages[name]) else: print(name+',you are not in the list') name='kiwi' if name not in languages.keys(): print('Come on \n---------------\n') else: print('What ?\n---------------\n') # 按顺序遍历字典中的所有键 for name in sorted(languages.keys()): print(name) print('\n') for name in sorted(languages.keys(),reverse=True): print(name) print('\n') # 遍历字典中的所有值 languages['Liam']='Python' for language in languages.values(): print(language) for language in sorted(languages.values(),reverse=True): print(language) # set 可以去除掉值中的重复值(键本身唯一 所以不需要) for language in set(languages.values()): print(language)
# 6-4 词汇表2:既然你知道了如何遍历字典,现在请整理你为完成练习6-3 而编写 # 的代码,将其中的一系列print 语句替换为一个遍历字典中的键和值的循环。确定 # 该循环正确无误后,再在词汇表中添加5 个Python 术语。当你再次运行这个程序 # 时,这些新术语及其含义将自动包含在输出中。 cihuibiao={ 'PHP':'超文本预处理器', 'range':'用于生成指定范围内的数字的函数', 'if':'条件判断语句', '元组':'不可变的列表', '字典':'类似php里的数组', '迭代':'遍历', '遍历':'迭代', '布尔表达式':'True or False', '切片':'部分使用列表lists[2:5],第三个到第四个', } for name,meaning in cihuibiao.items(): print(name+':\n\t'+meaning) # 6-5 河流:创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键— # 值对可能是'nile': 'egypt'。 # 使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。 # 使用循环将该字典中每条河流的名字都打印出来。 # 使用循环将该字典包含的每个国家的名字都打印出来。 rivers={'nile':'egypt','changjiang river':'china','lanchang river':'india'} for river,country in rivers.items(): print('The '+river.title()+' runs through '+country.title()+'.\n') for river in rivers.keys(): print(river.title()+'\n') for country in rivers.values(): print(country.title()+'\n') # 6-6 调查:在6.3.1 节编写的程序favorite_languages.py 中执行以下操作。 # 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人 # 未包含在字典中。 # 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未 # 参与调查的人,打印一条消息邀请他参与调查。 languages={ 'Tina':'C', 'Emily':'C#', 'Kiwi':'Python', } namelist=['Tina','liam','bob'] for name in namelist: if name in languages.keys(): print('Thx '+name.title()) else: print('I invite you,'+name)
# 如何在一个列表里嵌套很多个外星人的信息?
# 字典列表
alien_0={'color':'green','x':5,'y':4}
alien_1={'color':'red','x':3,'y':-1}
alien_2={'color':'yellow','x':-12,'y':5}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
# 自动创建三个属性相同的外星人
new_aliens=[]
for alen_num in range(0,30):# 1,31
new_aliens.append({'color':'red','x':2,'y':alen_num})
for alien in new_aliens[0:5]:
print(alien)
for alien in new_aliens[0:3]:
if alien['color']=='red':
alien['color']='yellow'
alien['x']+=3
for alien in new_aliens[0:3]:
print(alien)
# 在字典中存储列表
# 例如,你如何描述顾客点的pizza呢
pizza={
'name':'kiwi',
'peiliao':['土豆','牛肉','小番茄']
}
print(pizza['name']+',你预定了一个汉堡,他有如下配料:\n')
for peiliao in pizza['peiliao']:
print('\t'+peiliao)
f_language={
'Kiwi':['python','php','vue'],
'Tina':['html','vue'],
'Emily':['js','java','jsp','c#'],
'Stanley':['english']
}
for name,lang in f_language.items():
if len(lang)>1:
print(name+' loves these languages are:')
else:
print(name + ' loves language is:')
for item in lang:
print('\t'+item)
print('\n')
# 在字典中存储字典
users={
'0001':{
'name':'Kiwi',
'age':25,
'sex':'male'
},
'0002':{
'name':'Tina',
'age':30,
'sex':'female'
} ,
'0003':{'name':'Liam','age':31,'sex':'male'}
}
for code,profile in users.items():
print('编号: '+code+' 的个人资料如下:')
for item,detail in profile.items():
print('\t'+item+' : '+str(detail))
print('\n')
# 6-7 人:在为完成练习6-1 而编写的程序中,再创建两个表示人的字典,然后将这 # 三个字典都存储在一个名为people 的列表中。遍历这个列表,将其中每个人的所有信 # 息都打印出来。 kiwi={ 'first_name':'Kiwi', 'last_name':'qing', 'age':25, 'city':'Chengdu', } tina={ 'first_name':'Tina', 'last_name':'wang', 'age':26, 'city':'Chengdu', } liam={ 'first_name':'liam', 'last_name':'li', 'age':26, 'city':'Chengdu', } persons=[kiwi,tina,liam] for person in persons: for item,detail in person.items(): print(item+' : '+str(detail)) print('\n') # 6-8 宠物:创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在 # 每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列 # 表中,再遍历该列表,并将宠物的所有信息都打印出来。 doufu={'type':'cat','boss':'kiwi'} mangzi={'type':'dog','boss':'mige'} wugui={'type':'turtle','boss':'jiage'} pets=[doufu,mangzi,wugui] for pet in pets: for type,boss in pet.items(): print(type+':'+boss) print('\n') # 6-9 喜欢的地方:创建一个名为favorite_places 的字典。在这个字典中,将三个 # 人的名字用作键;对于其中的每个人,都存储他喜欢的1~3 个地方。为让这个练习更有 # 趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字 # 及其喜欢的地方打印出来。 favorite_places={ 'Kiwi':['Finland','Japan','China'], 'Shine':['Japan','France','Italy'], 'Sunny':['Vietnam','Thailand'], 'Dingding':['Japan'], } for name,places in favorite_places.items(): if len(places)>1: print(name+' likes these places: ') else: print(name+' likes this place: ') for place in places: print(place) print('\n') # 6-10 喜欢的数字:修改为完成练习6-2 而编写的程序,让每个人都可以有多个喜欢 # 的数字,然后将每个人的名字及其喜欢的数字打印出来。 favorite_num={ 'Kiwi':[1,7], 'Shine':[2,5], 'Liam':[3,7,6], 'Emily':[2,4,5,6,7], 'Tina':[9], } for name,nums in favorite_num.items(): if len(nums)>1: print(name+' likes these numbers:') else: print(name+' likes this number:') for num in nums: print(num) print('\n') # 6-11 城市:创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城 # 市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市 # 的事实。在表示每座城市的字典中,应包含country、population 和fact 等键。将每座 # 城市的名字以及有关它们的信息都打印出来。 cities={ 'Mianyang':{ 'country':'china', 'population':13, 'fact':'mifen is really delicious', }, 'Tokoyo':{ 'country':'japan', 'population':1, 'fact':'AV is so hot', }, 'newyork':{ 'country':'USA', 'population':3, 'fact':'I like Tesla', }, } for name,details in cities.items(): print('These are some information of '+name.title()+':') for item,detail in details.items(): print('\t'+item.title()+' : '+str(detail)) print('\n') # 打印所有城市的名字(打印字典的键) # 如果要打印字典的值,就用 dictionar.values() for name in cities.keys(): print(name.title()) # 删除绵阳的信息 del cities['Mianyang'] for name in cities.keys(): print(name.title())
# 函数input()的工作原理 message = input("Tell me something, and I will repeat it back to you: ") print(message) # 通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚 # 地知道其输入始于何处 name=input('Could you tell me your name?: ') print('OK,'+name+' I know your name now') # 使用int()来获取数值输入 age=input('How old are you ? : ') age=int(age) if age >= 18: print('You are not a baby now old man!') else: print('You are not a man little boy ~') # 求模运算符 % print(4%3) # 如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。你可利用这一点来判 # 断一个数是奇数还是偶数 number=int(input("告诉我一个数字,我会告诉你它是奇数还是偶数")) if number % 2 == 0: print('你输入的'+str(number)+'是一个偶数') else: print('你输入的'+str(number)+'是一个奇数') # Python 2.7也包含函数input(),但它将用户输入解读为Python代码,并尝试运行它们。因此, # 最好的结果是出现错误,指出Python不明白输入的代码;而最糟的结果是,将运行你原本无意运 # 行的代码。如果你使用的是Python 2.7,请使用raw_input()而不是input()来获取输入。
# 7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息, # 如“Let me see if I can find you a Subaru”。 brand=input('哈啰,你想租个啥子车嘛?说哈嘛: ') print('让我qio一眼,我能不能帮你找一过'+brand.title()) # 7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过8 人,就打印一 # 条消息,指出没有空桌;否则指出有空桌。 number=int(input('先森,恰饭哇,几位吶? ')) if number > 8: print('嗨呀,'+str(number)+'大'+str(number)+'过人,没得空桌子咯~') else: print('阔以阔以,刚好有个八仙桌,够你几爷子坐的了~') # 7-3 10 的整数倍:让用户输入一个数字,并指出这个数字是否是10 的整数倍。 number=int(input('来,说个数字,我看一哈是不是10的整数倍: ')) if number % 10 == 0: print('哈哈,就是10的倍数') else: print('哦豁,不是的')
# while 循环简介 # for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条 # 件不满足为止 number=int(input('来免费叫哥哥的时候到了,想让我叫你多少声哥哥: ')) if number < 0: number=1 count=0 while count<number: print('小哥哥') count+=1 # 让用户选择何时退出 lists=[] message='来告诉我你想去哪里耍,说完了的话就输个quit,来嘛: ' place="" while place.lower() != 'quit': place = input(message) if place.lower() != 'quit': lists.append(place) print("你想去的地方有这些:") for item in lists: print('\t'+item) # 使用标志 # 这样做的好处显而易见,即使有多种情况可以结束循环,我们也只需要在循环体了进行 # 条件判断,随时可以结束循环,而之前的程序只限制在用户输入了'quit' lists=[] message='来告诉我你想去哪里耍,说完了的话就输个quit,来嘛: ' place="" active=True while active: place = input(message) if place.lower() != 'quit': lists.append(place) else: active=False print("你想去的地方有这些:") for item in lists: print('\t'+item) # 要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 # break语句 lists = [] message = '来告诉我你想去哪里耍,说完了的话就输个quit,来嘛: ' place = "" active = True while active: place = input(message) if place.lower() != 'quit': lists.append(place) else: break print("你想去的地方有这些:") for item in lists: print('\t' + item) # 在循环中使用continue # 例如让程序只打印0-100中的偶数 number=0 while number <= 100: number+=1 if number % 2 != 0: continue print(number)
# 7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入 # 'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添 # 加这种配料。 active=True while active: message=input('add something: ') if message=='quit': print('End') break print('add: '+message) # 7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到3 岁的观众免费; # 3~12 岁的观众为10 美元;超过12 岁的观众为15 美元。请编写一个循环,在其中询问 # 用户的年龄,并指出其票价。 active=True while active: age=int(input('How old are you ? ')) if age <= 0: print('End') break elif age<3: print('free') elif age<12: print('$10') elif age>=12: print('$15') # 7-6 三个出口:以另一种方式完成练习7-4 或练习7-5,在程序中采取如下所有做法。 # 在while 循环中使用条件测试来结束循环。 # 使用变量active 来控制循环结束的时机。 # 使用break 语句在用户输入'quit'时退出循环。 print('看上面的代码') # 7-7 无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl +C, # 也可关闭显示输出的窗口)。 active=True while active: print('I love Shine !')
Python学习笔记 项目地址: https://github.com/LittleFee/python-learning-note
版权声明:
作者:Kiwi
链接:https://www.qingwei.tech/programe-develops/888.html
来源:清渭技术小站
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
共有 0 条评论