简体   繁体   English

如何打破无限的 Python 循环?

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

I'm looking to fix the following code, so that it can finish successfully for all numbers listed.我正在寻找修复以下代码,以便它可以成功完成列出的所有数字。 How can I break the infinite loop that's present?我怎样才能打破存在的无限循环? Furthermore, how can I return print(is_power_of_two(8)) as True?此外,如何将 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()

Use this.用这个。 From Check if a given number is power of two in Python检查给定的数字是否是 Python 中的 2 的幂

your while condition should be :你的while条件应该是:

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

cause for the moment your code infinitely loops when n=1 cause 1%2 = 1暂时导致您的代码在 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 Loops While 循环

make the print_prime_factors function print all the prime factors of a number.使 print_prime_factors 函数打印一个数字的所有质因数。 A prime factor is a number that is prime and divides another without a remainder.质因数是质数并能整除另一个数而没有余数。

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

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