-1

I'm new to python or coding in general. And encountered some while loop question in the following code.


a = int(input('input a number here: '))

def largest_factor(x):   
    factor = x - 1
    while factor > 0:
        if x % factor == 0:
             return factor
        factor -= 1
        print(factor)

largest_factor(a)

I'm using python 3.5, and in my understanding, the loop will not break until 0 > 0, so I put the print(factor) to exam that, however, it stopped at the largest factor(e.g. when x = 100, factor prints from 99 all the way to 50, and stopped), and did not reach 0. Is the return statement killed the while loop? Thank you for your time.

Psidom
  • 209,562
  • 33
  • 339
  • 356
dex
  • 77
  • 4
  • 13
  • 2
    yes because a return ends a function, you can `yield factor` then either `print(list(largest_factor(a)))` or iterate over the generator function `for f in largest_factor(a):print(f)` http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python – Padraic Cunningham Sep 04 '16 at 00:25
  • The `return` statement doesn't affect the `while` loop directly; rather it exits the function, `largest_factor(x)`. You can keep the loop alive using `yield` instead, if your goal was to call `largest_factor` repeatedly and have the loop keep generating values. – Jeff Sep 04 '16 at 00:26
  • Suspicious question. Too perfectly elaborated to bring the attention of many well meaning developers. – jgomo3 Sep 04 '16 at 03:55

2 Answers2

0

There are two ways to leave this loop, waiting until the while statement terminates or by returning the factor.

Charles Merriam
  • 19,908
  • 6
  • 73
  • 83
0

Your assumption is correct. Once the loop hits the return statement, the function will end. Since 100 is divisible by 50, the loop ends with the function ending.