1

I'm trying to create a function that uses one of its parameters to create a global variable with that parameter name. When I try to use the function and input a parameter it just says "name 'Matrix' is not defined"

def Gen2D(name, length):
    name = [[0 for j in range(length)] for i in range(length)]
    return(name)

Gen2D(Matrix, 12)

I want this to result in a 12 by 12 matrix with variable name "Matrix" but I get the error: "name 'Matrix' is not defined"

2299momo
  • 25
  • 1
  • 4
  • 4
    That sounds like you haven't learned how to use return values normally yet. Function parameters are for communicating information into a function, not for communicating results out. – user2357112 Oct 23 '19 at 00:25
  • 1
    An assignment like `name =` can be nothing other than an assignment to the variable literally named `name`. The way you get function results into a variable of your choice is to assign the function's return value: `Matrix = Gen2D(12)`. – jasonharper Oct 23 '19 at 00:25
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Oct 23 '19 at 00:25
  • Welcome to Stack Overflow! Check out the [tour]. There are lots of things wrong with this code: 1) `Matrix` is simply not defined; is it supposed to be a string? 2) Variable variables are evil; see the possible duplicate I linked. **Edit**: actually @jasonharper is right, you should use an assignment statement. 3) Anything involving matrices should probably be done with NumPy. 4) `return` is not a function, so don't put its argument in parens - but that's more of a nitpick than a genuine problem. – wjandrea Oct 23 '19 at 00:26
  • 1
    What's wrong with having only a `length` parameter and then doing something like `Matrix = Gen2D(12)`? Also, global variables really aren't as useful as you likely think they are. – Karl Knechtel Oct 23 '19 at 00:45

1 Answers1

3

So I am not quite following the global part of this question.

You could just do this:

def Gen2D(length):
    name = [[0 for j in range(length)] for i in range(length)]
    return name

Matrix = Gen2D(12)

If you really want it to be a global variable, you could instantiate and update a global variable within the function like so:

def Gen2D(length):
    global Matrix 

    # Updating the value of the global matrix variable (will be updated outside the function)
    Matrix = [[0 for j in range(length)] for i in range(length)] 

# Calling the function to update the global variable.
Gen2D(12)
sawezo
  • 305
  • 1
  • 8