Python Forum

Full Version: What is the meaning of k in this function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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
Ohhh boy...
Sorry for the question... of course k is an instance of range(2, n)...
Makes sense.

Highly appreciate your help buddy.

G
(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)