You need to declare the i
variable within the recebe_m
function. The same problem will occur with the variable n_divisores
, declare the same within the function.
m = int(input("Digite um numero inteiro:"))
def recebe_m(m):
n_divisores = 0
i = 1
while(i <= m/2):
if(m%i==0):
n_divisores = n_divisores + 1
i = i+1
if(n_divisores==1):
return(1)
else:
return(0)
print(recebe_m(m))
In addition, as the friend of the other response said, you are trying to divide by 0 in the first iteration of your while loop, correct this and initialize i
with 1.
The problem with your code is variable scope. In python if you declare a variable in a more internal scope, and the same variable exists in a global scope, the innermost scope variable will be the one used by python to do the calculations.
In your code you try to declare and increment a variable on the same line in a case where the i
variable does not exist in the inner scope yet, which causes the error. The same goes for n_divisores
.
To better understand:
x = 10
def func():
x = 5
print(x)
func() # printa 5
print(x) # printa 10, x com valor 5 morreu.
Edit: As @Anderson said, you do not have to check all the numbers, but only half of them (i <=m/2)