csev/py4e

Code error in Chapter 7 (search.py)

nishkalavallabhi opened this issue · 3 comments

A student of mine found a erroneous code sample in Chapter 7 - both in the html and the associated .py file. (https://www.py4e.com/code3/search7.py)

Here is what it says in the code:

fname = input('Enter the file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened:', fname)
    exit()
count = 0
for line in fhand:
    if line.startswith('Subject:'):
        count = count + 1
print('There were', count, 'subject lines in', fname)

-The problem with this is: if the file name is wrong or the file cannot be read (i.e., the code block in try fails and it goes to except), it still tries to do the remaining operations (reading the file in the for loop) and throws an error. The exit() somehow did not work. That whole part should have been in the try block itself. It was okay for us, as the student could ask me, but I guess for people learning on their own, this could confuse them. Please edit this.

csev commented

I just tried this and if the file name is bad, the exit() causes the code to stop so the for loop does not run. I tested this in Python3 on my macintosh. I wonder if other environments treat exit() differently. What system / operating system was your student using?

It is most likely windows (and it is Python3+) - because I was able to run it on my linux machine too, without any errors. I ran it myself on her computer by screen share (I couldn't see the OS as the IDE was full screen) and I also got the same error.

IDEs can do different things with exit(), this is one of the reasons the course runs code at command > or terminal $ prompts. It would be impossible to test and provide notes for all the issues with IDEs.