w3resource logo


Python Exercises

Python Challenges: Check if a given positive integer is a power of three

Python Challenges - 1: Exercise-2 with Solution

Write a Python program to check if a given positive integer is a power of three.

Input : 9
Output : True

Explanation :

Python: A positive integer is a power of 3

Sample Solution :-

Python Code :

def is_Power_of_three(n):
    while (n % 3 == 0):
         n /= 3;         
    return n == 1;

print(is_Power_of_three(9))
print(is_Power_of_three(81))
print(is_Power_of_three(21))

Output :

True                                                                    
True                                                                    
False

Flowchart:

Python Flowchart: Check if a given positive integer is a power of three

Python Code Editor:

def is_Power_of_three(n):
    while (n % 3 == 0):
         n /= 3;         
    return n == 1;

print(is_Power_of_three(9))
print(is_Power_of_three(81))
print(is_Power_of_three(21))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Python: How to check whether a file exists using Python?

C#: Loops in c#

PHP: For each

SQL: JOIN using more than 5 tables

JavaScript: Blank Slide in Javascript Slideshow