“无”从对“.get()”问题的调用返回
从调用返回 None.get()可能意味着未找到键或在字典中的键处找到的值实际上是 None。
那么如果在布尔测试中没有找到并且解释为 0,我可以将返回值设置为什么?
写这个:
ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
age = ages.get(person, ?) #what need to be '?'
if age:
print(f'{person} is {age} years old.')
else:
print(f"{person}'s age is unknown.")
回答
您不需要使用.get. 只需直接访问字典值。
像这样:
ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
try:
age = ages[person]
if age:
print(f'{person} is {age} years old.')
else:
print(f"{person}'s age is unknown.")
except KeyError:
print(f"Unknown person: {person}")