if
1 #第五章if语句 2 #每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试 3 cars = ['audi', 'bmw', 'subaru', 'toyota'] 4 for car in cars: 5 if car == 'bmw': #粗心 两个等号 6 print(car.upper()) 7 else: 8 print(car.title()) 9 10 # 一个等号是陈述;car = 'bmw'可解读为“将变量car 的值设置为'audi' ” 11 # 两个等号是发问;car == 'bmw'可解读为“变量car 的值是'bmw' 吗?” 12 13 #在Python中检查是否相等时区分大小写,例如,两个大小写不同的值会被视为不相等: 14 # >>> car = 'Audi' 15 # >>> car == 'audi' 16 # False 17 18 #函数lower() 不会修改存储在变量car 中的值,因此进行这样的比较时不会影响原来的变量: 19 # ❸ >>> car = 'Audi' 20 # ❷ >>> car.lower() == 'audi' 21 # True 22 # ❸ >>> car 23 # 'Audi' 24 """在❶处,我们将首字母大写的字符串'Audi' 存储在变量car 中;在❷处,我们获取变量car 的值并将其转换为小写, 25 再将结果与字符串'audi' 进行比较。这两个字符串相同,因此Python返回True 。从❸处的输出可知,这个条件测试并 26 没有影响存储在变量car 中的值。 27 网站采用类似的方式让用户输入的数据符合特定的格式。例如,网站可能使用类似的测试来确保用户名是独一无二的, 28 而并非只是与另一个用户名的大小写不同。用户提交新的用户名时,将把它转换为小写,并与所有既有用户名的小写版 29 本进行比较。执行这种检查时,如果已经有用户名'john' (不管大小写如何),则用户提交用户名'John' 时将遭到 30 拒绝。""" 31 32 >>> requested_toppings = ['mushrooms', 'onions', 'pineapple'] 33 # ❶ >>> 'mushrooms' in requested_toppings 34 # True 35 # ❷ >>> 'pepperoni' in requested_toppings 36 # False 37 # 在❶处和❷处,关键字in 让Python检查列表requested_toppings 是否包含'mushrooms' 和'pepperoni' 。这种技术 38 # 很有用,它让你能够在创建一个列表后,轻松地检查其中是否包含特定的值。 39 40 41 # 还有些时候,确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字not in 。例如,如果有一个列表, 42 # 其中包含被禁止在论坛上发表评论的用户,就可在允许用户提交评论前检查他是否被禁言: 43 banned_users = ['andrew', 'carolina', 'david'] 44 user = 'marie' 45 if user not in banned_users:#❶ 46 print(user.title() + ", you can post a response if you wish.") 47 #❶处的代码行明白易懂:如果user 的值未包含在列表banned_users 中,Python将返回True ,进而执行缩进的代码行。 48 49 #练习5-1 p46 50 car = 'maserati' 51 print("Is the car == 'Maserati'? I predict True.") 52 print(car == 'maserati') 53 54 print("Is the car == 'BMW'? I predict False.") 55 print(car == 'BMW') 56 57 a = "She likes me." 58 b = 'She likes me.' 59 print(a == b) 60 61 a1 = "She likes me." 62 b1 = 'she likes me.' 63 print(a1.lower() == b1) 64 print(a1 == b1,'\n'+'*' * 40 + '\n') 65 66 a3 = 138 67 b3 = 888 68 print(a3 == b3) 69 print(a3 != b3) 70 print(a3 > b3, a3 < b3, a3>=b3, a3<=b3) 71 print(a3 >= b3 and a3 < 100 , a3 <= b3 or a3 < 100) 72 73 grils = ('phyllis','shiitakeimoto') 74 print('phyllis' in grils) 75 print('harashima' not in grils) 76 77 78 input('Your age') 79 age = int(input()) #问题 如何输入年龄后转换为数值 80 input("yourasd") 81 age = int(raw_input()) 82 age = 66 83 if age < 4: 84 cost = 0 85 elif age >= 4 and age <= 18: 86 cost = 5 87 elif age >= 65: 88 cost = 5 89 else: 90 cost = 10 91 # y = chr(cost) 92 # x = 'Your admission cost is ' + '.' + y #问题 字符串 + 数字为何输出不了 93 print("Your admission cost is $" + str(cost) + ".") 94 """else 是一条包罗万象的语句,只要不满足任何if 或elif 中的条件测试,其中的代码就会执行,这可能 95 会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif 代码块来代替else 代码块。 96 这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。 97 重点:如果你只想执行一个代码块,就使用if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的if 语句。 98 """
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 = 0 28 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' in favorute_fruits: 43 print('You really like ' + favorute_fruits[0] + '!') 44 if 'watermelon' in favorute_fruits: 45 print('You really like ' + favorute_fruits[1] + '!') 46 if 'lemon' in favorute_fruits: 47 print('You really like ' + favorute_fruits[2] + '!') 48 if 'pear' in favorute_fruits: 49 print('You really like ' + favorute_fruits[3] + '!') 50 if 'peach' in favorute_fruits: 51 print('You really like ' + favorute_fruits[4] + '!') 52 53 requested_toppings = ['mushromms','greed peppers','extra cheese'] 54 for requested_topping in requested_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 if requested_toppings: 64 for requested_topping in requested_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 in requested_toppings: 76 if requested_topping in available_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 in user_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 def all_lower(L1): 98 return [s.lower() for s in L1] 99 L1 = ['admin','ryo','Phyllis','eric','jack'] 100 101 for new_user in new_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'] = 0 137 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 = 1 149 elif alien_0['speed'] == 'medium': 150 x_increment = 2 151 else: 152 # 这个外星人的速度一定很快 153 x_increment = 3 154 # 新位置等于老位置加上增量 155 156 alien_0['x_position'] = alien_0['x_position'] + x_increment 157 print("Now x-position: " + str(alien_0['x_position'])) 158 159 160 if alien_0['speed'] == 'slow': 161 x_increment = 1 162 elif alien_0['speed'] == 'medium': 163 x_increment = 2 164 else: 165 x_increment = 3 166 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 in favorite_languages.keys(): 207 print(name.title()) 208 if name in friends: 209 print(" Hi " + name.title() + 210 ", I see your favorite language is " + 211 favorite_languages[name].title() + "!") 212 if 'erin' not in favorite_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 in sorted(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 in favorite_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 in set(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 in like_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)