Python Forum
What is the meaning of k in this function? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: What is the meaning of k in this function? (/thread-29039.html)



What is the meaning of k in this function? - giladal - Aug-15-2020

Dear all,

I am in the process of learning python and going through the mod operator.
I am having a hard time understanding what is the meaning of k in the following. Why does it decide k == 2?

Highly appreciate your support.


def smallest_factor(n):
    for k in range(2, n):
        if n % k == 0:
            return k

ans = smallest_factor(33)
if ans == 3:
    print("CORRECT: 3 is the smallest factor of 33")
else:
    print("WRONG: 3 is the smallest factor of 33 but the code returned", ans)



RE: What is the meaning of k in this function? - buran - Aug-15-2020

range(2, n) will yield all numbers from 2 to n-1.
Because in loop, k will take each of these value and you will test if n%k is 0, i.e. n is divisible by k. the function will return first such value


RE: What is the meaning of k in this function? - giladal - Aug-15-2020

Ohhh boy...
Sorry for the question... of course k is an instance of range(2, n)...
Makes sense.

Highly appreciate your help buddy.

G


RE: What is the meaning of k in this function? - buran - Aug-15-2020

(Aug-15-2020, 12:18 PM)giladal Wrote: of course k is an instance of range(2, n)...
no, it's not an instance of range object. because of the loop, it takes the values (int), produced by range, one by one in each iteration of the loop.
you can visualise the execution here: http://www.pythontutor.com/visualize.html

compare

def smallest_factor(n):
    numbers = range(2, n)
    print(f'numbers is {type(numbers)}')
    for k in numbers:
        print(f'k is {type(k)}')
        if n % k == 0:
            return k
smallest_factor(33)