今天的内容包括if语句以及字典的操作。
# 检查是否不相等
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)
# 在字典中存储字典,操作方法类似,省略
整体运行结果:
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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。