Isaac Dzikum
Isaac Dzikum

Reputation: 313

While loop with an integer condition?

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

Answers (2)

sog
sog

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

Mark Ransom
Mark Ransom

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

Related Questions