Use of python Return

Asked

Viewed 1,085 times

-3

def repita():
    x = 2
    while n % x != 0:
    x += 1
repeat()
while n > 1:
    n = n / x #aqui se encontra o primeiro problema, já que "n" não é reconhecido fora da função
    x += 1
    if n % x != 0:#mesmo problema de antes
        repita() #aqui a função se repetiria aumentando o valor do "x"

My question is about how to use the Return so that "n" and "x" are recognized and I can work with them.

  • Extract? Divide one by the other? This question is not making much sense. Explain better what you are doing and what you want as a result for each input.

  • I edited the question, my doubt became clearer?

  • What I don’t understand is what that function is. Why does it exist? What does "repeat" mean? It seems to be doing several things. Why not simply declare n and x outside?

  • My algorithm is still in its infancy, so I don’t know if it’s worth posting it in its entirety just to make sense of that stretch, so I used as an example this function that doesn’t make much sense thinking it would be easier to understand the doubt, but anyway I will edit and put the function of my code.

1 answer

1


This is due to the rules of scope.

x is created inside the repeat function, and ceases to exist as soon as the function ends.

To get the final value of x you need to write something like

def repita:
    x = 2
    return x
x2 = repita()

Return sends the value of x outside the scope of the function, and this value is assigned to the variable x2.

it is not recommended to have a variable that will be accessed throughout the program (global variable), but it is possible.

x = 2
def repita:
    x = 5
x = x + 5

As the initial definition is outside the function the value is changed inside and outside the function.

Browser other questions tagged

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