Home > Mobile >  Is it possible to make these lines of code any shorter? Like use a list in some way in order to not
Is it possible to make these lines of code any shorter? Like use a list in some way in order to not

Time:06-22

I made a dictionary for converting months and i want to make the code shorter for the "Not a valid key" print. I have tried using a list but it didn't work, maybe I did it wrong?

print("To close the program type \"Terminate\"")


def main():

    month_convertor = {
        "Jan": "January",
        "Feb": "February",
        "Mar": "March",
        "Apr": "April",
        "May": "May",
        "Jun": "June",
        "Jul": "July",
        "Aug": "August",
        "Sep": "September",
        "Oct": "October",
        "Nov": "November",
        "Dec": "December",
    }

    a = "Jan"
    b = "Feb"
    c = "Mar"
    d = "Apr"
    f = "May"
    g = "Jun"
    h = "Jul"
    i = "Sep"
    j = "Oct"
    k = "Nov"
    n = "Dec"

    m = input("Please enter the first 3 digits of the month: ")
    print(month_convertor.get(m))
    if m == a or m == b or m == c or m == d or m == f or m == g or m == h or m == i or m 
== j or m == k or m == n\
            or m == "Terminate":
        "# print(\"Not a valid key\")"
    else:
        print("Not a valid key")
    while m != "Terminate":
   


main()

CodePudding user response:

You don't need to test against a, b, c, ... You already have the dictionary month_convertor, which you can test against:

def main():
    month_convertor = {
        "Jan": "January",
        "Feb": "February",
        "Mar": "March",
        "Apr": "April",
        "May": "May",
        "Jun": "June",
        "Jul": "July",
        "Aug": "August",
        "Sep": "September",
        "Oct": "October",
        "Nov": "November",
        "Dec": "December",
    }

    choice = input("Please enter the first 3 digits of the month: ")
    choice = choice.title()  # convert to title case
    if choice in month_convertor:
        # Do something
    elif choice == "Terminate":
        # Do the termination
    else:
        # Do the invalid key
  • Related