繁体   English   中英

如何打破无限的 Python 循环?

[英]How do I break an infinite Python loop?

我正在寻找修复以下代码,以便它可以成功完成列出的所有数字。 我怎样才能打破存在的无限循环? 此外,如何将 print(is_power_of_two(8)) 返回为 True?

  # 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


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

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

def is_power_of_two(n): # Check if the number can be divided by two without a remainder while n!=0 and (n % 2 == 0 or 2%n==0): n = n / 2 return True return False
import math    
math.log2(number).is_integer()

用这个。 检查给定的数字是否是 Python 中的 2 的幂

你的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

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

While 循环

使 print_prime_factors 函数打印一个数字的所有质因数。 质因数是质数并能整除另一个数而没有余数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM