1
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?

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

Comments

1

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.

7 Comments

Well, it's never going to be "null". Python doesn't even have that. "As long as y has a value that is not zero" would be more accurate.
My understanding is that null == 0 == False in Python but you are absolutely correct from a formal, mathematical perspective. So thank you for your clarification!
Python has None, but not "null". If we're being picky, there are a whole set of things that are "false-ish", all of which work as Booleans.
Your latest edit isn't wrong (except for misspelling None) but it's a little misleading since there's no way y could be None.
@sog Your assumption that "null == 0 == False" is false, even if we use "None == 0 == False". You can check that with a simple print(None == 0).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.