Jump to content

Code mistake in the python course in topic Python Try...Except


Recommended Posts

While learning python from w3schools, I encountered a bug in the code in the section Python Try...Except. While explaining Finally concept, there is one example given to explain the Finally block

  f = open("demofile.txt")
  f.write("Lorum Ipsum")
  print("Something went wrong when writing to the file")
  f.close()   #Compilation issue. Not correct

This code is giving the below compilation issue

Traceback (most recent call last):
  File "try.py", line 8, in <module>
NameError: name 'f' is not defined

It is because if "demofile.txt" is not present then open will failed to open and nothing will get assigned to the f.

f variable will be none. So when it will execute the f.close() code written in the finally block,  it will through the compilation error as it is trying to close some invalid file descriptor.

Please have a look into this issue and let me know if my understanding is correct



Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...