条件测试
age = 0
age == 0 and age == 1 # and————&&
age == 0 or age == 1 # or————||
list = [1, 2, 3]
print(1 in list) # 一个值在列表里返回True
print(2 not in list) # 不在一个列表返回True
if list:
pass # 该if来判断列表是否为空,不为空返回True,为空返回False
字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color']) # 访问
alien_0['x'] = 25 # 访问不存在的元素直接是添加
point_value = alien_0.get('green', 'no key') # 第一个参数指定键,第二个参数指定键不存在时的返回值
for key, value in alien_0.items(): # 遍历字典
print(f"\nkey:{key}")
print(f"value:{value}")
for name in alien_0.keys(): # 遍历键
print(name.title())
for name in alien_0: # 遍历字典时默认遍历键
print(name.title())
for name in sorted(alien_0.keys()): # 按特定顺序遍历
print(name)
for value in alien_0.values(): # 遍历值
print(value)
for value in set(alien_0.values()): # 遍历不含重复元素的值
print(value)
字典相关嵌套
# 字典列表
alien0 = {'color': 'green', 'points': 5}
alien1 = {'color': 'red', 'points': 10}
alien2 = {'color': 'yellow', 'points': 15}
aliens = [alien0, alien1, alien2]
# 字典中存储列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# 字典存储字典
users = {
'aeinstein':{
'first': 'albert',
'second': 'esinstein',
},
'mcurie': {
'first':'marie',
'second':'curie',
}
}
使用input
message = input("something:") # 参数为要向用户显示的提示信息
print(int(message)) # 字符串转int
用while处理列表和字典
# 删除特定值的所有元素
pets = [1, 2, 1, 3, 1, 4]
while 1 in pets:
pets.remove(1)
print(pets)
# 使用用户输入填充字典
responses = {}
flag = True
while flag:
name = input("first")
response = input("second")
responses[name] = response
repeat = input("quit?")
if repeat == "y":
break
print(responses)