Search code examples
pythoncs50

Is there a function I can use to replace my if statements and variables?


I'm trying to figure out how to make my code more readable and have less lines in my code. It contains a lot of if elif statements that seem like can be combined into a few.

fl = input("file:").lower().strip()

a = fl.endswith(".jpeg")
b = fl.endswith(".jpg")
c = fl.endswith(".txt")
d = fl.endswith(".png")
e = fl.endswith(".pdf")
f = fl.endswith(".zip")
g = fl.endswith(".gif")

if a or b is True:
    print("image/jpeg")
elif c is True:
    print("text/plain")
elif d is True:
    print("image/png")
elif e is True:
    print("application/pdf")
elif f is True:
    print("application/zip")
elif g is True:
    print("image/gif")
else:
    print("application/octet-stream")

I tried getting rid of the variables on the top by putting fl == fl.endswith(".filetype") inside of the if statements, and instead of printing each type it only printed my else statement. I also tried looking up other ways to get the end of the str in python docs but couldn't find anything. Don't give me too direct of a solution to the problem, would like to avoid cs50 academic honesty issues. Also still quite new to python


Solution

  • Use a dictionary to map extensions to content-types.

    import os
    
    extension_content_types = {
        ".jpeg": "image/jpeg",
        ".jpg": "image/jpeg",
        ".txt": "text/plain",
        ".png": "image/png",
        ".pdf": "application/pdf",
        ".zip": "application/zip",
        ".gif": "image/gif",
    }
    
    fl = input("file:").lower().strip()
    filename, ext = os.path.splitext(fl)
    content_type = extension_content_types.get(ext, 'application/octet-stream')
    
    print(fl, content_type)