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, c-40, -2):
        if (n%i) == 0:
            print "p = ", i 
            i = p
            print p 


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

  • answered 2018-02-13 02:06 Ctznkane525

    Have the function return a value:

    def brute(c):
        for i in range(c, c-40, -2):
            if (n%i) == 0:
                print "p = ", i 
                return i 
    d = brute(c)

    Then use d

  • answered 2018-02-13 02:07 pstatix

    Your assignment is backwards, p = i not i = p. The implementation of the operator= (the =) in Python takes the right-hand side (RHS) and assigns it to the left-hand 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
            int myInt;
            // 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 the operator= is the RHS. Thus we access the myInt attribute of each object and assign the value of the RHS to the LHS.

  • answered 2018-02-13 02:08 Lightness Races in Orbit

    i = p

    This means "set i equal to the value of p".

    If you really wish to "transfer" the value of i to p, then your assignment is backwards.