Skip to content
Advertisement

How to make a variable inside a try/except block public?

How can I make a variable inside the try/except block public?

JavaScript

This code returns an error

JavaScript

How can I make the variable text available outside of the try/except block?

Advertisement

Answer

try statements do not create a new scope, but text won’t be set if the call to url lib.request.urlopen raises the exception. You probably want the print(text) line in an else clause, so that it is only executed when there is no exception.

JavaScript

If text needs to be used later, you really need to think about what its value is supposed to be if the assignment to page fails and you can’t call page.read(). You can give it an initial value prior to the try statement:

JavaScript

or in the else clause:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement