Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this variable considered local?

I have this code:

with open("01-1-input.txt", "r") as f:
inputs = [int(i[:-2] if i[-1] == "n" else i) for i in f.readlines()]

total_mass = 0

def calculate_fuel_for_mass(mass):
    fuel_for_mass = mass // 3 - 2
    if fuel_for_mass > 0:
        total_mass += fuel_for_mass
        calculate_fuel_for_mass(fuel_for_mass)
    else:
        return 0

for i in inputs:
    calculate_fuel_for_mass(i)

print(total_mass)

And it's throwing an UnboundLocalError: local variable 'total_mass' referenced before assignment.

Why is that? I thought any variable declared in the main scope is global?

like image 267
Capyryan Avatar asked Sep 14 '26 20:09

Capyryan


1 Answers

The line

total_mass += fuel_for_mass

can be thought of as equivalent to

total_mass = total_mass + fuel_for_mass

Given a setup like this, python sees an assignment happening to a variable in local scope (inside the function).

A minimal demonstration of this behaviour can be seen as follows:

var = 42
def f():
    var = var + 1
#    var += 1 would also show the same behaviour

f() #UnboundLocalError: local variable 'var' referenced before assignment

Python infers that there is a local variable total_mass because it sees an assignment to the variable in the local scope. However, the local variable total_mass has not been assigned a value, and so you see the error as shown.

You can use the global keyword before the assignment to access the variable in the global scope as follows

var = 42
def f():
    global var
    var = var + 1

f() #var is now 43 in global scope
like image 67
Paritosh Singh Avatar answered Sep 17 '26 09:09

Paritosh Singh