Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to make these lines of code any shorter? Like use a list in some way in order to not need to use this many variables?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading