【问题标题】:Python begginer - Can someone tell me why this loop don't finish?Python begginer - Can someone tell me why this loop don\'t finish?
【发布时间】:2022-12-01 22:21:52
【问题描述】:
def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  if n != 0:
    return False

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

This is a excercice from Coursera's Python course. I don't know why it don't finish when n=0.

【问题讨论】:

  • When you pass n = 0 then n = n / 2 will continue to re-assign 0 to n, and therefore the condition for your while loop is always True
  • Writing solution @Tomerikoo
  • Why I was down voted

标签: python


【解决方案1】:

while n % 2 == 0: will turns out to be a infinate loop.

This happening because

First number input is 0

while n % 2 == 0: ---> 0 ==0 --> True

While True:
    #This is infinate loop.

Code correction

To avoid this check if n is zero or not before while.

def is_power_of_two(n):

  if n ==0:
      return False
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  if n != 0:
    return False



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

Gives #

False
True
True
False

【讨论】:

  • You changed the while into if. It should still be while.
  • @RufusVS not seen that just updated
猜你喜欢
  • 2022-12-02
  • 2022-12-01
  • 2022-12-02
  • 2022-12-01
  • 2022-12-02
  • 2022-12-27
  • 2021-12-30
  • 2022-12-01
  • 2022-12-02
相关资源
最近更新 更多