18python入门到精通_2.18 python入门到精通 第五章if语句 第六章字典

1 #练习5-3 p 49

2 alien_color = 'green'

3 if alien_color == 'green':4 print('you got 5 points.')5 if alien_color == 'red':6 print('you got 5 points.')7 if alien_color == 'yellow':8 print('you got 5 points.')9

10 if alien_color == 'green':11 print('you got 10 points.')12 else:13 print('you got 10 points.')14 if alien_color == 'green':15 print('you got 5')16 if alien_color != 'green':17 print('you got 10 points')18

19 if alien_color == 'green':20 x = 5

21 elif alien_color == 'yellow':22 x = 10

23 elif alien_color == 'red':24 x = 15

25 print('you got'+ str(x) + 'points.')26

27 age =028 if age < 2:29 print('He is a babe.')30 elif age >= 2 and age<=4:31 print('He is learning to walk.')32 elif 4 < age <= 13:33 print('He is a child.')34 elif 13 < age <= 20:35 print('He is a teenager')36 elif 20 < age <= 65:37 print('He is a adult.')38 elif age > 65:39 print('He is a aged.')40

41 favorute_fruits = ['apple','watermelon','lemon','pear','peach']42 if 'apple' infavorute_fruits:43 print('You really like' + favorute_fruits[0] + '!')44 if 'watermelon' infavorute_fruits:45 print('You really like' + favorute_fruits[1] + '!')46 if 'lemon' infavorute_fruits:47 print('You really like' + favorute_fruits[2] + '!')48 if 'pear' infavorute_fruits:49 print('You really like' + favorute_fruits[3] + '!')50 if 'peach' infavorute_fruits:51 print('You really like' + favorute_fruits[4] + '!')52

53 requested_toppings = ['mushromms','greed peppers','extra cheese']54 for requested_topping inrequested_toppings:55 if requested_topping == 'green peppers':56 print("Sorry, we are out of green peppers right now.")57 else:58 print("Adding" + requested_topping + ".")59 print("\nFinished making your pizza!")60

61

62 requested_toppings =[]63 ifrequested_toppings:64 for requested_topping inrequested_toppings:65 print("Adding" + requested_topping + ".")66 print("Finished making your pizza!")67 else:68 print("Are you sure you want a plain pizza?")69

70 available_toppings = ['mushrooms', 'olives', 'green peppers',71 'pepperoni', 'pineapple', 'extra cheese']72

73 requested_toppings = ['mushrooms', 'french fries', 'extra cheese']74

75 for requested_topping inrequested_toppings:76 if requested_topping inavailable_toppings:77 print("Adding" + requested_topping + ".")78 else:79 print ('Sorry,we don\'t have' + requested_topping + '.')80 #错打成requested_toppings时 由最后一个print遍历requested_toppings

81 #把列表中的 'french fries'去掉,使avai包含requ时,输出结果为遍历requ剩下的2个元素

82 print ('Finished making your pizza!')83

84

85 #练习5-8

86 user_names = ['admin','ryo','phyllis','eric','jack']87 for user_name inuser_names:88 if user_name == 'admin':89 print('Hello'+ user_name.title() + ',would you like to see a status report?')90 else:91 print('Hello' + user_name.title() + ',thank you for logging in again.')92 else:93 print('We need to find some users!')94

95 curren_users = ['admin','ryo','Phyllis','eric','jack'] #转换小写通过下文def函数实现 *重点*

96 new_users = ['admin','ryo','phyllis','Shiitakeimoto','Harashima']97 defall_lower(L1):98 return [s.lower() for s inL1]99 L1 = ['admin','ryo','Phyllis','eric','jack']100

101 for new_user innew_users:102 if new_user.lower() in all_lower(L1): #,如果用户名'John' 已被使用,应拒绝用户名'JOHN

103 print(new_user.title() + ',Please input other name.')104 else:105 print(new_user.title() + ',Congratulation!You can use this name.')106

107 for num in range(1,10):108 if num == 1:109 print(str(num) + 'st')110 elif num == 2:111 print(str(num) + 'nd')112 elif num == 3:113 print(str(num) + "rd")114 else:115 print(str(num) + 'th')116 """PEP 8提供的唯一建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格,117 例如,if age < 4: 要比if age<4: 好。118 想想你可能想编写的游戏、想研究的数据集以及想创建的Web应用程序。"""

119 #6.1 字典

120 """鉴于字典可存储的信息量几乎不受限制,因此我们会演示如何遍历字典中的数据。121 另外,你还将学习存储字典的列表、存储列表的字典和存储字典的字典。理解字典后,122 你就能够更准确地为各种真实物体建模。你可以创建一个表示人的字典,然后想在其123 中存储多少信息就存储多少信息:姓名、年龄、地址、职业以及要描述的任何方面。124 你还能够存储任意两种相关的信息,如一系列单词及其含义,一系列人名及其喜欢的125 数字,以及一系列山脉及其海拔等。"""

126

127 alien_0 = {'color': 'green', 'points': 5}128 new_points = alien_0['points']129 print("You just earned" + str(new_points) + "points!")#如果你在有外星人被射杀时都运行这段代码,就会获取该外星人的点数。

130

131 #6.2.2 添加键—值对

132 #字典是一种动态结构,可随时在其中添加键—值对。要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值。

133 alien_0 = {'color':'green','point': 5}134 print(alien_0)135

136 alien_0['x_position'] =0137 alien_0['y_posision'] = 25

138 print(alien_0)#Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系。

139 #使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,通常都需要先定义一个空字典。

140 """

141 #重点 alien_0['speed'] = 'fast'这行位置不同输出的速度不同142 alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}143 print("Original x-position: " + str(alien_0['x_position']))144 # 向右移动外星人145 # 据外星人当前速度决定将其移动多远146 alien_0['speed'] = 'fast'147 if alien_0['speed'] == 'slow':148 x_increment = 1149 elif alien_0['speed'] == 'medium':150 x_increment = 2151 else:152 # 这个外星人的速度一定很快153 x_increment = 3154 # 新位置等于老位置加上增量155

156 alien_0['x_position'] = alien_0['x_position'] + x_increment157 print("Now x-position: " + str(alien_0['x_position']))158

159

160 if alien_0['speed'] == 'slow':161 x_increment = 1162 elif alien_0['speed'] == 'medium':163 x_increment = 2164 else:165 x_increment = 3166 print("New x-position: " + str(alien_0['x_position']))167 """

168 #练习6-1

169 id = {'first_name':'Phyllis',170 'last_name':'Ryo',171 'age':'20',172 'city':'Sydney'

173 }174 id['age'] = '23'

175 print(id)176

177 like_number = {'phyllis': '1','shiitakeimoto': '223','ergou':'88','erzi':'66','momoe':'667'}178 print('Phyliss\'s favorite number is :' + like_number['phyllis'])179 print('shiitakeimoto\'s favorite number is :' + like_number['shiitakeimoto'])180 print('ergou\'s favorite number is :' + like_number['ergou'])181 print('erzi\'s favorite number is :' + like_number['erzi'])182 print('momoe\'s favorite number is :' + like_number['momoe'])183

184 python_vocabulary = {'import this':'Zen of python',185 'insert':'插入',186 'range':'范围',187 'input':'投入',188 'popped':'术语弹出'

189 }190 print(python_vocabulary)191

192 for vocabulary,means in python_vocabulary.items():#第二部分包含字典名和方法items()

193 print('\nvocabulary:'+vocabulary)194 print('means:' +means)195

196

197 在不需要使用字典中的值时,方法.keys() 很有用198

199 favorite_languages ={200 'jen': 'python',201 'sarah': 'c',202 'edward': 'ruby',203 'phil': 'python',204 }205 friends = ['phil', 'sarah']206 for name infavorite_languages.keys():207 print(name.title())208 if name infriends:209 print("Hi" + name.title() +

210 ", I see your favorite language is" +

211 favorite_languages[name].title() + "!")212 if 'erin' not infavorite_languages.keys():213 print("\nErin, please take our poll!")214

215 #6.3.3 按顺序遍历字典中的所有键

216 favorite_languages ={217 'jen': 'python',218 'sarah': 'c',219 'edward': 'ruby',220 'phil': 'python',221 }222 for name insorted(favorite_languages.keys()):223 print(name.title() + ", thank you for taking the poll.")224

225 #6.3.4 遍历字典中的所有值

226 favorite_languages ={227 'jen': 'python',228 'sarah': 'c',229 'edward': 'ruby',230 'phil': 'python',231 }232 print("The following languages have been mentioned:")233 for language infavorite_languages.values():234 print(language.title())235

236 #为剔除重复项,可使用集合(set)

237 favorite_languages ={238 'jen': 'python',239 'sarah': 'c',240 'edward': 'ruby',241 'phil': 'python',242 }243 print("The following languages have been mentioned:")244 for language inset(favorite_languages.values()):245 print(language.title())246 python_vocabulary = {'import this':'Zen of python',247 'insert':'插入',248 'range':'范围',249 'input':'投入',250 'popped':'术语弹出'

251 }252 id = {'first_name':'Phyllis',253 'last_name':'Ryo',254 'age':'20',255 'city':'Sydney'

256 }257 id['age'] = '23'

258 print(id)259

260 like_number = {'phyllis': '1','shiitakeimoto': '223','ergou':'88','erzi':'66','momoe':'667'}261 for name inlike_number:262 print(name + '\'s favorite number is :' + like_number[name] + '.')263 print('Phyliss\'s favorite number is :' + like_number['phyllis'])264

265

266 python_vocabulary = {'import this':'Zen of python',267 'insert':'插入',268 'range':'范围',269 'input':'投入',270 'popped':'术语弹出'

271 }272 print(python_vocabulary)273

274 for vocabulary,means in python_vocabulary.items():#第二部分包含字典名和方法items()

275 print('\nvocabulary:'+vocabulary)276 print('means:' + means)

你可能感兴趣的:(18python入门到精通)