0

I am to create a function that has to generate a squared array where all values are populated by 0 and 1, being 0 always the first character.

While I've solved the first part via np.full function; now I got stuck at the second part. Please see my 2 attempts below:

First attempt:

%matplotlib inline
import matplotlib as plt
import numpy as np
import matplotlib.pyplot as plt
M = np.full((N, O), (0, 1), dtype=int)
N = M.shape[0] #N represents M's number of rows
O = M.shape[1] #O represents M's number of columns

def sqm(N): 
    while  N == O: #While  N and O are different
        if  N !=  O: #If they are really different
            O = N #Then O will equate to N
            return(M)
    
print(sqm(5))

By doing this I get an error type: UnboundLocalError: local variable 'O' referenced before assignment. So I looked it up on this very platform. A suitable solution to this would be either put the variables inside the function or marking them as 'global'.

Here it goes my second attempt:

%matplotlib inline
import matplotlib as plt
import numpy as np
import matplotlib.pyplot as plt

M = np.full((N, O), (0, 1), dtype=int)
N = M.shape[0] #N represents M's number of rows
O = M.shape[1] #O represents M's number of columns
    

def sqm(N):
    global M, N, O
    while  N == O: #While  N and O are different
        if  N !=  O: #If they are really different
            O = N #Then O will equate to N
            return(M)

print(sqm(5))

However, now I'm getting the following error: SyntaxError: name 'N' is parameter and global.

Before turning to you, I consulted the following post but it didn't shed any light on this (or I'm too dumb to pick up on the solution): Name 'x' is parameter and global [Python]

Said that, could you please help me understand what am I doing wrong?

Thank you very much in advance!

mozway
  • 194,879
  • 13
  • 39
  • 75
MadMarx17
  • 71
  • 7
  • In your funtction, N is referring to both the input parameter, and the global variable N you declared. – gshpychka Nov 15 '21 at 21:20
  • `while N == O: #While N and O are different` your code says the exact opposite of your comment – diggusbickus Nov 15 '21 at 22:31
  • `M = np.full((N, O), (0, 1), dtype=int)` will fail even if you assign `O` and `N` – diggusbickus Nov 15 '21 at 22:31
  • The `UnboundLocalError` is because you're trying to use variable `N` and `O` to create `M` before you've even defined what they are. And then you're also trying to create `N` and `O` from M - you can't define things in this "chicken and egg" way - you need to create things in order. The syntax error is because you can't use the same variable name as an argument to `sqm` and as a global in the function (if you fix this by removing N as an argument, you will get the UnboundedLocalError` again. – Peter Nov 15 '21 at 22:49

0 Answers0