是否可以在 except 语句中捕获 None?

Is it possible to catch None in except statement?

我正在开发一个代表月份的程序。 每个月的名称和数字都存储在字典中,键是月份名称。

程序需要将月份名称作为输入,输出对应的数字。 如果提供的输入不是月份,则输出 "Not found"
如果输入不是一个月,它总是 returns None
如何做到这一点?
我的代码:

mon ={"January":1,
      "February":2, 
      "March":3,
      "April":4,
      "May":5,
      "June":6,
      "July":7,
      "August":8,
      "September":9,
      "October":10,
      "November":11,
      "December":12
}
try:
    num = input()
    print(mon.get(num))
except KeyError:
    print("Not found")

get()如果没有key可以return一个默认值。 您得到的 None.get() 的默认 return 值。

def foo(x):

    mon = {"January": 1,
           "February": 2,
           "March": 3,
           "April": 4,
           "May": 5,
           "June": 6,
           "July": 7,
           "August": 8,
           "September": 9,
           "October": 10,
           "November": 11,
           "December": 12
           }

    return mon.get(x, "Not found")
>>> print(foo("Test"))
'Not found'
>>> print(foo("July"))
7

语法:.get("key","Default value")

Docs