Home > Mobile >  Why does this function return True for this variable?
Why does this function return True for this variable?

Time:05-27

Taking an online course on python and the assignment was to break the loop and make the function work properly. While I was able to solve the problem, I did not understand why the function returns (and is supposed to) "True" for number 8.

Could you please explain?

def is_power_of_two(n):
  while n % 2 == 0 and n != 0:
    n = n / 2
  if n == 1:
    return True
  return False

print(is_power_of_two(0)) # False
print(is_power_of_two(1)) # True
print(is_power_of_two(8)) # True
print(is_power_of_two(9)) # False

Here is how I interpreted it:

  1. 8 divided 2 gives a remainder of 0: First condition is met.
  2. 8 is not equal to 0: Second condition is met.
  3. If (while) both conditions are met, the number (8) is divided by 2 and this value (4) is assigned to variable n.
  4. Finally, it checks if the variable n (4) is equal to 1. Since 4 is not equal 1 it should return False, but instead it returns True. Why is that?

CodePudding user response:

"If" and "while" don't mean quite the same thing, either in English or in Python (in English the difference is similar to "when" vs "while").

The while loop repeats while (as long as) the condition is true; it doesn't only happen once if the condition is true. As long as the condition is met, the body of the loop is executed, and then the condition is re-checked. For the starting value n = 8, the loop is executed three times before it stops. Each time the body of the loop is executed, n is halved.

  1. n = 8: 8 is even and not 0, so the loop executes and continues.
  2. n = 4: 4 is even and not 0, so the loop executes and continues.
  3. n = 2: 2 is even and not 0, so the loop executes and continues.
  4. n = 1: 1 is not even, so the loop ends.
  5. After the loop: n = 1, so we return True.
  • Related