How to access variables defined in another function?

Asked

Viewed 3,836 times

3

I’m writing a show about the NIM game. He asks me to call functions within another function, but when I try to compute variables belonging to this function in another function (the function that calls the one that contains the variable) an error message appears saying that it does not identify the variable name. I tried every way to fix it, but I couldn’t:

def computador_escolhe_jogada(n,m):
    m2 = 1
    while (m2 <= m) and (((n-m2)%(m+1)) != 0):
        m2 = m2 + 1
        return m2


def usuario_escolhe_jogada(n,m):  
    m1 = int(input('Quantas peças você vai tirar? '))
    while m1 > m:
        print()
        print('Oops! Jogada inválida! Tente de novo.')
        print()
    return m1
    print('O jogador removeu',m1,' peças')

def partida():

    n = int(input('n? '))
    m = int(input('m? '))
    while n > 0:
        if (n%(m+1) == 0):
            print('Você começa!!!')
            usuario_escolhe_jogada(n,m)
            print('Agora restam', n - m1,'peças no tabuleiro')

        if (n%(m+1)!=0):
            print('O computador começa')
            computador_escolhe_jogada(n,m)
            print('Agora restam', n - m2,'peças no tabuleiro')
        n = n - m1 - m2

He says that the m1 is not set, but it is set yes, only in the top function. How do I recognize the other function?

Hello everyone thanks for the contributions. It turns out that if I store M1 = user_choice(n,m) m2 = computer_choice played(n,m)

The program simply executes the functions once more and does not return the variables. And exercise requires no global variables (this is a requirement of exercise :)

  • In the current context, there is no m1. Why not pass m1 and m2 as parameters?

  • Taking advantage, is there any way to properly format your code? Just select it and press Ctrl+k

  • What game is this? What are the rules of this game ?

  • Maybe it’s worth reading from: Python - NIM game

  • Hello everyone, I am new to STACK OVERFLOW, this is my first question, sorry for the mistakes. Thanks for all your help. The rules of the game are as follows

2 answers

3

When you set a variable within of a function, this variable exists only during the execution time of the function. In order for you to use the values of M1 or m2, they should be global variables, or be stored in some way. Let’s go in parts:

def computador_escolhe_jogada(n,m):
    m2 = 1
    while (m2 <= m) and (((n-m2)%(m+1)) != 0):
        m2 = m2 + 1
        return m2

Your first function takes two parameters o n and the m and uses them to make the respective calculations inherent in the game and store in the variable m2. Mote that you declare the variable within of the function, so, as I said above, it only exists during the execution of the function.

How to solve? :

Note that its functions return values, that is to say they become values, so it is possible to store these values in variables. Thus:

def computador_escolhe_jogada(n,m):
    m2 = 1
    while (m2 <= m) and (((n-m2)%(m+1)) != 0):
        m2 = m2 + 1
        return m2

m2 = computador_escolhe_jogada(10,20) # Valores hipotéticos 

Thus the declared variable out of of the scope of the function assumes the value of its function, in this case the value of m2.

Okay, but how does that work out ?

.
.
.
n = int(input('n? '))
m = int(input('m? '))
while n > 0:
    if (n%(m+1) == 0):
        print('Você começa!!!')
        m1 = usuario_escolhe_jogada(n,m)
        print('Agora restam', n - m1,'peças no tabuleiro')

    if (n%(m+1)!=0):
        print('O computador começa')
        m2 = computador_escolhe_jogada(n,m)
        print('Agora restam', n - m2,'peças no tabuleiro')
    n = n - m1 - m2

Your mistake was probably on that line : print('Agora restam', n - m1,'peças no tabuleiro') Note that the program could not call m1 because she was a variable that existed only within its functions

When you store the result of these functions in global variables:

m1 = usuario_escolhe_jogada(n,m)
m2 = computador_escolhe_jogada(n,m)

The program recognizes them and can deal with their values.

I hope I’ve helped you somehow.

1

You could also choose to use "global" within the function. This would allow you to view the variable within that scope. Example:

def exemplo():
    global X 
    X = 'Valor da Variável'
    return X

In this case, if you print the value of the variable X, though outside the function (if you have already run the function, of course). It will have the value "Variable Value" that was defined within the function.

  • 1

    It’s an alternative. I think it’s not great for the AP, but it’s a valid alternative. I’d let the code a little closer to the doubt

Browser other questions tagged

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