Search code examples
pythonloopsdatenames

The assignment: Prompt user to input their Birthmonth then input the day they were born. Print the month's name followed by the day


I tried doing it the long way by simply going down the months one by one but my teacher told me the long was was unacceptable. Now I have the day and month printed but am not sure how to quickly change the number given into the month it represents. This is what I have so far.

    birthMonth = int(input("Enter your Birth Month:"))

if birthMonth <= 0 or birthMonth > 12:
   print("Invalid, Choose again")
else:
    birthDay = int(input("What day?:"))
    if birthDay <=0 or birthDay > 31:
        print('Not a valid Birthday')
    else:
        print(birthMonth, birthDay)

It will print the number and the day which is fine but she does not want me to list out all of the months. I would appreciate any help I can get.


Solution

  • You can use the datetime module to get the month associated with a number.

    >>> import datetime
    >>> month_num = 8
    >>> month = datetime.date(2017, month_num, 1).strftime("%B")
    >>> print(month)
    August
    

    Another alternative (probably the better one) is to use the calendar module

    >>> import calendar
    >>> month_num = 8
    >>> calendar.month_name[month_num]
    August
    

    So, in your code, you can replace

    print(birthMonth, birthDay)
    

    with

    print(calendar.month_name[birthMonth], birthDay)
    

    but, make sure that you import the calendar module.