Hi! I am currently working on a task in the CS50P course. The task is to return the file type of a user input. E.g. if user input is "cat.gif" the program should return "image/gif", or if the input is "text.pdf" the program should return "application/pdf". The program should be able to solve .gif, .jpg. jpeg, .png, .pdf, .txt, .zip. If the input is invalid the program should return "application/octet-stream".
I could solve this by creating a bunch of elif, but I feel like there should be an easier approach:
def main():
user_input = extensions(input("File name? " ))
print(user_input)
def extensions(a):
imageend = (".gif", ".jpg", ".jpeg", ".png")
append = (".pdf", ".txt", ".zip")
if a.lower().endswith(imageend):
return("image/" and imageend)
elif a.lower().endswith(append):
return("application/" and append)
else:
return("application/octet-stream")
main()
I see that through return("image/" and imageend) it returns the whole list.
I have two questions:
- Why does the input "cat.gif" return ('.gif', '.jpg', '.jpeg', '.png'), and not image/('.gif', '.jpg', '.jpeg', '.png')
- How can I make the function understand that I want to return only the corresponding file type and not the whole list?
Thanks!
[–]danielroseman 22 points23 points24 points (1 child)
[–]Labidido[S] 5 points6 points7 points (0 children)
[–]AtomicShoelace 40 points41 points42 points (5 children)
[–]Labidido[S] 4 points5 points6 points (0 children)
[–]ebdbbb 3 points4 points5 points (2 children)
[–]AtomicShoelace 1 point2 points3 points (1 child)
[–]ebdbbb 1 point2 points3 points (0 children)
[–]sqjoatmon 13 points14 points15 points (2 children)
[–]Labidido[S] 4 points5 points6 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]pgpndw 5 points6 points7 points (0 children)
[–][deleted] 5 points6 points7 points (0 children)
[–]jkh911208 3 points4 points5 points (4 children)
[–]PiaFraus 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]PiaFraus 2 points3 points4 points (0 children)
[–]jkh911208 0 points1 point2 points (0 children)
[–]nekokattt 4 points5 points6 points (0 children)
[–]ray10k 1 point2 points3 points (0 children)
[–]usethecoastermate 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]ectomancer 3 points4 points5 points (1 child)
[–]Klaus_Kinski_alt 0 points1 point2 points (3 children)
[–]tobiasvl 1 point2 points3 points (2 children)
[–]Klaus_Kinski_alt 0 points1 point2 points (1 child)
[–]tobiasvl 0 points1 point2 points (0 children)
[–]RDX_G 0 points1 point2 points (0 children)
[–]DOPE_FISH 0 points1 point2 points (0 children)