Accessing Variables Declared Inside A With Block Outside Of It - Why Does It Work?
I'm starting to learn some Python and found out about the with block. To start of here's my code: def load_words(): ''' Returns a list of valid words. Words are strings of
Solution 1:
You can read the variables inside a with block because the with statement does't add any scope to your program, it's just a statement to make your code cleaner when calling the object you refer in it.
This:
withopen('file.txt', 'r') as file:
f = file.read()
print(f)
Outputs the same as:
file = open('file.txt', 'r')
f = file.read()
file.close()
print(f)
So the main difference is that makes your code cleaner
Post a Comment for "Accessing Variables Declared Inside A With Block Outside Of It - Why Does It Work?"