Reputation: 313
def gcd(x, y):
while(y): x, y = y, x % y
return x
The function above returns the greatest common divisor of two numbers. Why is y used as the condition in the while loop?
Upvotes: 1
Views: 967
Reputation: 532
This is used because the x % y
will reduce y to the remainder of x / y (also called modulo) with each iteration of the loop. So the loop will execute as long as y 'is true' or in other words as long as y has a value that is not None
or zero.
Upvotes: 1
Reputation: 308140
The expression in a while
statement will be evaluated as a boolean. An integer of 0
will evaluate to False
, everything else will evaluate to True
.
Your statement is equivalent to while y != 0:
Upvotes: 1