In this case, the "all_lines" variable is initalised in the context manager, and it is accessible from the function "part_1".
total = 0
with open("advent_input.txt", "r") as txt:
all_lines = []
context_total = 0
for line in txt:
all_lines.append((line.rstrip().split(" ")))
def part_1():
# total = 0
for line in all_lines:
if line[0] == "A":
if line[1] == "Y":
total = 8
elif line[1] == "X":
context_total = 4
However, "context_total", which is also initalised in the context manager, does not work in the function "part_1". And "total" from the global scope does not work either. How come "all_lines" works?
CodePudding user response:
Python does not have general block scope, so anything assigned within the with
will be accessible outside of the block.
context_total
is different though since you're reassigning it within the function. If you assign within a function, the variable will be treated as a local unless you use global
to specify otherwise. That's problematic here though since =
necessarily must refer to an existing variable (or else what are you adding to?), but there is no local variable with that name.
Add global context_total
to use it within the function, or pass it in as an argument if you don't need the reassigned value externally.
CodePudding user response:
It works because inside the function, the all_lines
variable is referenced but not assigned. The other two variables are assigned.
If a variable is assigned inside a function, then that variable is treated as local throughout the function, even if there is a global variable of the same name.