Skip to main content

How to check if a number is a perfect cube in Python

How to check if a number is a perfect cube in Python.

Here's a step-by-step tutorial on how to check if a number is a perfect cube in Python:

Step 1: Get the input from the user

  • To check if a number is a perfect cube, we need to take an input number from the user. You can use the input() function to get the number as a string and then convert it to an integer using the int() function. Let's store the number in a variable called num.
num = int(input("Enter a number: "))

Step 2: Calculate the cube root of the number

  • To determine if a number is a perfect cube, we need to calculate its cube root. We can use the ** operator with a power of 1/3 to find the cube root. Let's store the cube root in a variable called cube_root.
cube_root = round(num ** (1/3))

Step 3: Check if the cube of the cube root is equal to the original number

  • To verify if a number is a perfect cube, we need to check if the cube of the cube root is equal to the original number. We can use an if statement to perform this check. If the condition is true, then the number is a perfect cube; otherwise, it is not.
if cube_root ** 3 == num:
print(num, "is a perfect cube.")
else:
print(num, "is not a perfect cube.")

Step 4: Complete code example

  • Here's the complete code example that puts all the steps together:
num = int(input("Enter a number: "))
cube_root = round(num ** (1/3))

if cube_root ** 3 == num:
print(num, "is a perfect cube.")
else:
print(num, "is not a perfect cube.")

Step 5: Additional example using a function

  • If you want to reuse the code for multiple numbers, you can create a function that checks if a number is a perfect cube. Here's an example:
def is_perfect_cube(num):
cube_root = round(num ** (1/3))
return cube_root ** 3 == num

num = int(input("Enter a number: "))

if is_perfect_cube(num):
print(num, "is a perfect cube.")
else:
print(num, "is not a perfect cube.")

That's it! You now have a step-by-step tutorial on how to check if a number is a perfect cube in Python.