今天的內容包括if語句以及字典的操做。post
# 檢查是否不相等 requested_topping = 'mushrooms' if requested_topping != 'anchovies': print("hold the anchovies") # 檢查特定值是否包含在列表中 requested_toppings = ['1', '2', '3'] if '1' in requested_toppings: print('true') banned_users = ['andrew', 'caroline', 'david'] user = 'marie' if user not in banned_users: print(user.title() + ', you can post a response if you wish.') # if-elif-else 肯定列表不是空的 requested_toppings = [] if requested_toppings: # 列表空等於False for requested_topping in requested_toppings: print("adding" + requested_topping + ".") print("\nFinished making your pizza!") else: print("Are you sure you want a plain pizza?") # 建立字典 alien_0 = {'color':'green', 'points':5} print(alien_0['color']) print(alien_0['points']) # 添加鍵-值對 alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) # 修改鍵-值對 alien_0['color'] = 'yellow' print(alien_0) # 刪除鍵-值對 del alien_0['points'] print(alien_0) # 刪除的鍵值對永遠消失了 # 遍歷字典全部的鍵-值對 for key, value in alien_0.items(): # items()返回一對鍵-值對 print("\nKey: " + key) print("Value: " + str(value)) # 遍歷字典全部的鍵 for name in alien_0.keys(): # keys()返回鍵 value()返回值 print(name.title()) # 使用set()方法找出獨一無二的元素 trial_0 = { '1': '11', '2': '22', '3': '22', } print('The following item is unique: ') for number in set(trial_0.values()): print(number.title()) # 字典列表 trial_1 = {'4':'44'} trial_2 = {'5':'55'} trial_3 = {'6':'66'} Trial = [trial_1, trial_2, trial_3] for ttrial in Trial: print(ttrial) # 在字典中存儲列表 trial_4 = { 'crust': 'thick', 'toppings': ['mushroom', 'extra cheese'] } print(trial_4['crust']) print(trial_4['toppings']) for topping in trial_4['toppings']: print('\t' + topping) # 在字典中存儲字典,操做方法相似,省略
總體運行結果:code
hold the anchovies true Marie, you can post a response if you wish. Are you sure you want a plain pizza? green 5 {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25} {'color': 'yellow', 'points': 5, 'x_position': 0, 'y_position': 25} {'color': 'yellow', 'x_position': 0, 'y_position': 25} Key: color Value: yellow Key: x_position Value: 0 Key: y_position Value: 25 Color X_Position Y_Position The following item is unique: 11 22 {'4': '44'} {'5': '55'} {'6': '66'} thick ['mushroom', 'extra cheese'] mushroom extra cheese