importing a file containing a function I wrote: no global variable

Asked

Viewed 66 times

0

Constroimatriz.py file:

"""
Escreva uma função que recebe um inteiro m e outro n e com isso
constrói uma matriz mxn
"""
matrix = []

def main():
    m = int(input("Digite o número de linhas da matriz: "))
    n = int(input("Digite o número de colunas da matriz: "))


    def matriz(m,n):

        for i in range(1,m+1):
            linha = []
            for j in range(1,n+1):

                x= int(input("Digite o valor ({},{}): ".format(i,j)))
                linha.append(x)

            global matrix    
            matrix.append(linha)

        return matrix


    print(matriz(m,n))


if __name__ == "__main__":
    main()

File Trocaelementosmatriz.py:

"""
Escreva uma função que troca um elemento por outro numa matriz
"""

#from ConstroiMatriz import matriz ##ConstroiMatriz.py que eu fiz
import ConstroiMatriz


def troca():

    pos1 = int(input("Digite a linha do elemento a ser trocado: "))
    pos2 = int(input("Digite a coluna do elemento a ser trocado: "))
    pos3 =int(input("Digite a linha do elemento a ser trocado: "))
    pos4 = int(input("Digite a coluna do elemento a ser trocado: "))

    global matrix

    matrix[pos1][pos2], matrix[pos3][pos4] = matrix[pos3][pos4],matrix[pos1][pos2]



matriz(1,1)    
troca()

Objective: to use the function matrix(m,n) defined in Constroimatriz.py in the program Trocaelementosmatriz.py and thus exchange 2 elements of the matrix created in Constroimatriz.

While running the Swap file smatriz.py, I get error :

matriz(1,1)
NameError: name 'matriz' is not defined

Any suggestions?

1 answer

2

The function def matriz(m, n) is declared within the function main(), so you can’t access def matriz(m, n) from nowhere but within main().

To solve it just take def matriz(m, n) from within the main().

def matriz(m,n):
    for i in range(1,m+1):
        linha = []
        for j in range(1,n+1):

            x= int(input("Digite o valor ({},{}): ".format(i,j)))
            linha.append(x)

        global matrix    
        matrix.append(linha)

    return matrix

def main():

    m = int(input("Digite o número de linhas da matriz: "))
    n = int(input("Digite o número de colunas da matriz: "))

    print(matriz(m,n))

if __name__ == "__main__":
    main()
  • main was not to contain my entire program? I did not understand well for what main!

  • And where do I put my Matrix = [] ?

  • now, when running Constrictmatrix the error is -> Nameerror: name’m' is not defined

  • So the problem you’re having is scope. It’s not really "import" the whole program.

  • I really don’t know! I’m trying to learn these concepts!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.