Answered step by step
Verified Expert Solution
Question
1 Approved Answer
python 3) Handling bad filenames Right now, if you pass in a bogus file name to your wordcount function (that is, the filename you input
python
3) Handling bad filenames Right now, if you pass in a bogus file name to your wordcount function (that is, the filename you input does not exist within the directory you are running the program from), you'll most likely get an error that looks something like this: FileNotFoundError: [Errno 2] No such file or directory: 'badfile.txt' We could deal with this by using Python's os module to search our current directory and check whether the file the user is asking for actually exists before opening it. But there's an easier way to approach the problem by using exception handling. A try-except block is another control flow structure in Python, that works somewhat similarly to an if statement. The difference is that Python will always attempt to execute the try clause first, and if any errors (exceptions) occur within the try clause, it will look for an except clause that matches the error that occurred, and start executing that code instead, without crashing the program. For example, the following program will attempt to input an integer from the user and set z to 2 divided by that number. However, two things could go wrong here: the user could input something that isn't an integer, causing a valueError when we try to use the int function on it, or the user could input 0. causing a ZeroDivisionError. try: x = int(input ("Enter a number")) z = 2/x print ("Good job, no errors") except ValueError: print("Input was not an integer, setting z to -1") z = -1 except ZeroDivisionError: print("Can't divide by 0, setting z to -2") z = -2 print (2) Run the code above enough times to test all possible paths through the try-except block, and be prepared to explain to the TA how many test runs are required. Then, add a try-except structure to your function from part 2 to prevent the function from crashing in the case that the file name the user inputs is not present in the directory. Instead, your function should just print "Bad file name" and return -1. The error you'll need to catch is a FileNotFoundErrorStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started