Use of return in python [closed]

-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 how to use return so that "n" and "x" are recognized and I can work with them.

    
asked by anonymous 24.12.2017 / 11:46

1 answer

1

This is because of the scope rules.

x is created inside the function repeat, and ceases to exist once the function terminates.

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

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

The return returns the value of x out of the scope of the function, and this value is assigned to the variable x2.

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

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

Since the initial definition is outside the function, the value is changed inside and outside the function.

    
24.12.2017 / 17:01