'None' 从调用“.get()”问题返回
'None' returned from a call to '.get()' issue
从对 .get()
的调用中获取 None returned 可能意味着未找到该键或者在字典中找到的键值实际上是 None.
那么,如果在布尔测试中没有找到并且解释为 0,我可以将 return 值设置为什么?
写这个:
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}")
在这种情况下,使用 try/except:
会很有用
ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
try:
age = ages[person] #what need to be '?'
if age:
print(f'{person} is {age} years old.')
else:
print(f"{person}'s age is unknown.")
except KeyError:
print(f'{person} not found in ages')
输出
Get age for: Jim
Jim is 30 years old.
Get age for: Kevin
Kevin's age is unknown.
Get age for: Bob
Bob not found in ages
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"{person} is not known.")
从对 .get()
的调用中获取 None returned 可能意味着未找到该键或者在字典中找到的键值实际上是 None.
那么,如果在布尔测试中没有找到并且解释为 0,我可以将 return 值设置为什么?
写这个:
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}")
在这种情况下,使用 try/except:
会很有用ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
try:
age = ages[person] #what need to be '?'
if age:
print(f'{person} is {age} years old.')
else:
print(f"{person}'s age is unknown.")
except KeyError:
print(f'{person} not found in ages')
输出
Get age for: Jim
Jim is 30 years old.
Get age for: Kevin
Kevin's age is unknown.
Get age for: Bob
Bob not found in ages
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"{person} is not known.")