用户输入宠物名称,如果在字典中找到,代码返回宠物的价格,否则要求用户尝试不同的名称。想知道这是否可以用更少的代码行以更简洁的方式完成?
pets = {'bird': 3.5, 'cat': 5.0, 'dog': 7.25, 'gerbil': 1.5}
while True:
req_pet = input("Enter pet name: ")
if req_pet in pets:
for (pet, price) in pets.items():
if pet == req_pet:
print(price)
exit(0)
else:
print("Pet not found, let's try a different one?")
Run Code Online (Sandbox Code Playgroud)
您可以通过执行以下操作来减少它:
try:
print(pets[input("Enter pet name: ")])
exit(0)
except KeyError:
print("Pet not found, let's try a different one?")
Run Code Online (Sandbox Code Playgroud)
这会在字典中明确查找输入“键”,并打印值并退出。如果密钥不存在,它会捕获错误并打印消息。
如果您不需要exit以这种方式,它可以变得更短,使用get返回默认消息代替:
print(pets.get(input("Enter pet name: "), "Pet not found, let's try a different one?")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |