Search code examples
pythondictionarytry-catchexcept

Is it possible to catch None in except statement?


I'm working on a program that represents a month in number. Each month name and number are stored in a dictionary, with the key being the month name.

The program needs to take the month name as input and output its corresponding number. In case the provided input is not a month, output "Not found"
It always returns None if input isn't a month.
How to do this?
My code:

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")

Solution

  • get() Can return a default value if there is no key. The None you were getting was the default return value for .get().

    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
    

    Syntax: .get("key","Default value")

    Docs