-2

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")
Python learner
  • 1,159
  • 1
  • 8
  • 20

1 Answers1

2

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

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
  • Thanks, it means we can't use try-except statements for this? – Python learner Mar 28 '22 at 06:21
  • 1
    No worries, You can use them if you'd like, but it's better not to. You would use `print(mon[num])` rather than `print(mon.get(num))` which would cause a key error. Or you could assign `x = mon[num]` before printing, so you skip to the except block before printing `None` – Freddy Mcloughlan Mar 28 '22 at 06:39