Is there a way to grab value "i" in a for loop?
I'm trying to get the value of i in a for loop, i'm trying to calculate n mod c, where c is a candidate. If c is a factor of n, the result will be zero.
import math
n = 2173
print "n = ", n
c = int(round(math.sqrt(n)))
p = 0
def brute(c):
for i in range(c, c40, 2):
if (n%i) == 0:
print "p = ", i
i = p
print p
brute(c)
The first i print, prints out 41, but when i try to transfer the i value into p and printing, I get p. It doesn't look like the value of i is even transferring into variable p. Anyway of getting the value of i? I want to return it and use it for the rest of my code.
3 answers

Have the function return a value:
def brute(c): for i in range(c, c40, 2): if (n%i) == 0: print "p = ", i return i d = brute(c)
Then use d

Your assignment is backwards,
p = i
noti = p
. The implementation of theoperator=
(the=
) in Python takes the righthand side (RHS) and assigns it to the lefthand side (LHS).So think of it as:
(RHS = LHS) == RHS.operator=(LHS)
. Inside the C code of Python, it is implemented in such a manner.For a broader example, consider something in C++. Suppose you had a
class MyClass
:class MyClass { private: int myInt; public: // nothing for simplicity };
Using the compiler provided default copy assignment here would be fine, and would look something along the lines of:
Myclass& MyClass::operator=(const MyClass& rhs) { this>myInt = rhs.myInt; // making the LHS 'myInt' equal to the RHS return *this; }
Now we dont need to get into the weeds of what all those symbols (if unfamiliar to you) do, but rather focus on the fact that
this
refers to the LHS of the equation, and the argument passed to theoperator=
is the RHS. Thus we access themyInt
attribute of each object and assign the value of the RHS to the LHS. 
i = p
This means "set
i
equal to the value ofp
".If you really wish to "transfer" the value of
i
top
, then your assignment is backwards.