如何打破一个无限的Python循环?

如何打破一个无限的Python循环?,python,Python,我希望修复以下代码,以便它能够成功地完成列出的所有数字。我怎样才能打破目前的无限循环? 此外,我如何将print(两(8)的幂)返回为True 用这个。从 用这个。从开始,您的while状态应为: # Check if the number can be divided by two without a remainder while n % 2 == 0 and n >1: n = n / 2 原因当n=1时,代码无限循环,原因1%2=1您的while条件应为: # Che

我希望修复以下代码,以便它能够成功地完成列出的所有数字。我怎样才能打破目前的无限循环? 此外,我如何将print(两(8)的幂)返回为True

用这个。从


用这个。从

开始,您的while状态应为:

# Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n >1:
    n = n / 2

原因当n=1时,代码无限循环,原因1%2=1

您的while条件应为:

# Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n >1:
    n = n / 2

因为当n=1时,代码无限循环,导致1%2=1

添加
和n!=0
到while条件,因此当n为0时循环将停止。

添加
和n!=0
切换到while状态,因此当n为0时循环将停止。

def为2(n)的幂:
#检查数字是否可以被二除而不带余数
而n=0和(n%2==0或2%n==0):
n=n/2
返回真值
返回错误
def是两个(n)的功率:
#检查数字是否可以被二除而不带余数
而n=0和(n%2==0或2%n==0):
n=n/2
返回真值
返回错误


您能修复代码示例中的缩进吗?断点位于没有任何意义的位置。将其移动到循环中。@Z4层代码已设置为其默认值。断点放在哪里?对于哪个数,你会得到一个无限循环?你对为什么最好的解释是什么?@KarlKnechtel我想是奇数吧?我不确定。您能修复代码示例中的缩进吗?
break
位于没有任何意义的位置。将其移动到循环中。@Z4层代码已设置为其默认值。断点放在哪里?对于哪个数,你会得到一个无限循环?你对为什么最好的解释是什么?@KarlKnechtel我想是奇数吧?我不确定。那里根本不需要循环。当然,这是为了适合他的例子,我也不知道他的计算方法这会停止循环,但我仍然需要检查这个函数中的数字是否是2的幂。这在@lamourettejean-baptiste中起作用,但它仍然返回(是2(8)的幂)为假。是的,这是因为这不是检查数字是否是二的幂的正确方法。我只是想打破你的无限循环。你只需要返回@ThomasDenisReyes回答的内容,而不是做一个while loopLoop,这里根本不需要。当然,这是为了适合他的例子,我也不知道他的计算方法这会停止循环,但我仍然需要检查这个函数中的数字是否是2的幂。这在@lamourettejean baptiste中起作用,但它仍然返回(是两(8)的幂)为False。是的,这是因为这不是检查数字是否是二的幂的正确方法。我只是想打破你的无限循环。你只需要返回@ThomasDenisReyes回答的内容,而不是做一个循环。我想,他根本不需要循环。这是怎么回事?我想,他根本不需要循环。这是怎么回事?
# Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n >1:
    n = n / 2
def is_power_of_two(n):

 #Check Number for Zero
  if n==0:
    return False
  else:
    # 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
    return False
def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n!=0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  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