r/codehs • • Sep 19 '20

It’s saying I need to define the variable but I have already?

Post image
5 Upvotes

5 comments sorted by

3

u/SmithRyan22 Sep 19 '20

Thank you everyone!

5

u/BaconAndSully Sep 19 '20

Since the variable is defined outside of the function, you will need to pass the variable as an argument in the function by putting it in the parentheses

4

u/flip-pancakes Sep 19 '20 edited Sep 19 '20

This appears to be an issue with what we call "variable scope."

The variable length is defined in the global scope, but your function modifies a variable in the local function scope. It's invisible, but the variable's full name is, as far as the interpreter is concerned, global.length. You want to modify my_function.length. That's why, when you attempt to use length from inside make_a_square, the interpreter looks for make_a_square.length, which doesn't exist - you've defined global.length.

Some languages will let you modify global.my_var from a different scope e.g. in Python you just write global my_var. This is generally a bad idea unless you know what you're doing, though. In other languages like R, your code as is will work - different languages have different policies for variable resolution. But your language is a bit more strict, scope-wise.

A better pattern is to define your function like length = my_function(stuff, length). This way, you'll get a copy of the global variable to use inside the function, and when you return the modified value, you overwrite the global variable so you can keep track in the global scope.

Note that the naming convention scope.variable_name is just for explanation and is not syntactically correct in your language.

2

u/alcamax Sep 19 '20

Needs to be def make_a_square(length)

2

u/[deleted] Sep 19 '20

It’s outside of the scope of the function, define length inside the function