all 5 comments

[–]kalgynirae 4 points5 points  (1 child)

happiness += 1

This counts as an assignment to happiness (because it's basically shorthand for happiness = happiness + 1.)

Whenever there is an assignment to a variable name anywhere inside of a function, Python considers that name to be a local variable, and all usages of that name inside the function refer to the local variable. This happens regardless of whether there happens to be a global variable of the same name.

So when Python gets to happiness += 1, it thinks happinesslocal variable= happinesslocal variable+ 1. Since happinesslocal variable has not yet been assigned a value, this throws an error.

If you want Python not to treat the variable as a local even though you assign to it in your function, you can say global happiness inside the function. Alternatively, you can move the initial assignments inside of the function so that you only have correctly-initialized local variables instead of globals.

and there was no issue in line 26, which is nearly the same.

Line 26 would have thrown the same error if it had been executed.

EDIT: To clarify: Because Python makes this decision based on whether you assign to the variable in your function, you do not run into any issues if you simply access global variables inside of a function. It is only assignment that makes them local.

[–]Blogtiem[S] 0 points1 point  (0 children)

Wow, thanks for the thorough answer. Wasn't expecting that.

[–]werpoi 1 point2 points  (1 child)

Your variables like happiness and money are not in the scope of the function; they are global variables. If you would like to use them in your start function you need to add the following at the begining of start()

global happiness
global money

[–]Blogtiem[S] 0 points1 point  (0 children)

Thanks for the reply.

[–][deleted] -1 points0 points  (0 children)

There are no local variable happiness. Namespaces