-1

First,it is giving me syntax error on while loop condition. To get rid of zero division error here, I have given the condition to while loop so that the number will not be equal to zero. Now, I don't know what to do?

def is_power_of_two(number):
  while (number!== 0 && number%2!=0):
    number = number / 2
   if number == 1:
     return True
   else
     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

I tried to solve it but it didn't worked.

  • (1) Your code's indentation is incorrect (2) Python uses `and` to join conditions, not `&&`. Please fix them first. – Hai Vu Apr 01 '23 at 13:06
  • could also use `is_power_of_two = lambda n: n>1 and bin(n)[3:].find('1') == -1` – arrmansa Apr 01 '23 at 16:20

1 Answers1

0

As I can see there is one syntax error, you missed ":" after else.

Also, I changes conditions in while loop. Right now it gives answers that you mentioned

def is_power_of_two(number):
    while (number > 1) & (number % 2 == 0):
        number = number / 2
    if number == 1:
        return True
    else:
        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

False
True
True
False

Ilya
  • 1
  • 1