script_8.py - File Extension Checker
Code
#!/usr/bin/env python3
"""File extension checker"""
filename = input("Enter filename: ")
if filename.endswith(".txt"):
print("Text file detected")
elif filename.endswith(".py"):
print("Python script detected")
elif filename.endswith(".jpg") or filename.endswith(".png"):
print("Image file detected")
else:
print("Unknown file type")
Explanation
Line 4: filename = input("Enter filename: ")
- input() returns string type (str)
- filename stores the user input as a string
Line 6: if filename.endswith(".txt"):
- .endswith() is a string method that returns boolean (True/False)
- Checks if the string ends with the specified suffix
- Case-sensitive comparison
- Returns True if filename ends with ".txt", False otherwise
Line 8: elif filename.endswith(".py"):
- Only evaluated if previous condition was False
- Another .endswith() check for different extension
Line 10: elif filename.endswith(".jpg") or filename.endswith(".png"):
- or logical operator returns True if EITHER condition is True
- Checks two different extensions in one elif
- Both .endswith() calls return booleans
- True if filename ends with either .jpg OR .png
Line 12: else:
- Catches all filenames that don't match any of the above extensions
- Fallback for unknown file types