-1
def monthName(): 
    NewDictionary = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June",\
    7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"}
monthNumber= int(input("Enter number "))
monthNumber= monthName
print(monthName)

I'm having trouble with this code. Every time I run it asks for the month number but won't print out the month name.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • Does this answer your question? [Get month name from number](https://stackoverflow.com/questions/6557553/get-month-name-from-number) – Aaron_ab Sep 13 '20 at 10:27
  • No, OPs question is far more basic than that. He just wants to query the dictionary using a key. – Akshay Sehgal Sep 13 '20 at 10:31
  • You define `monthName` as a function that takes no argument and returns nothing. You never call this function. And even if you called the function it wouldn't return anything. And it doesn't do any lookup in the dictionary. You seem to have missed some parts of your class, tutorial or book. – Some programmer dude Sep 13 '20 at 10:33

2 Answers2

0

Not sure what you are trying to do but your function does nothing but define a dict. Try this by putting everything inside the function and then actually getting the value for the respective key from the dictionary -

def monthName():
    
    #Define new dict
    NewDictionary = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June",\
    7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"}
    
    #Take input from user
    monthNumber = int(input("Enter number "))
    
    #Get month name with input month number as key and return output
    output = NewDictionary.get(monthNumber)
    return output

monthName() #function call
#input = 3
'March'
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

Using dict.get(key, 'default-val') with a default value:

A few things to take notes on:

  1. You could init the dict outside the function, in order to avoid creating it everytime you call the funciton.

  2. You could pass the monthNumber as an argument to the function monthName()

  3. Return the month name if found, else return a default value

Hence:

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

def monthName(monthNumber): 
    return NewDictionary.get(monthNumber, 'Month not found!')       

monthNumber= int(input("Enter number "))
print(monthName(monthNumber))

OUTPUT:

Enter number 2
February 

Enter number 44                                                                                                                                                              
Month Not found! 
DirtyBit
  • 16,613
  • 4
  • 34
  • 55