Python Program to Find Cube of a Number
The cube of a number is obtained by multiplying that number by itself twice. If we consider the number as 'n' then the cube of n is n*n*n and is represented as n^3. We are given a number and we have to find its cube value.
Example:
Input: 5
Output: 125
Explanation: 5 * 5 * 5 = 125
In this article, we aim to find the cube of a number in Python.
Python Programs to Find Cube of a Number
Now let us see different approaches to find the cube of a given number in Python.
Arithmetic Multiplication Operator
A simple and easy way is to manually multiply the number by itself twice by using the arithmetic multiplication operator. This method is clear and intuitive.
# function to find cube
def cube(num):
# arithmetic multiplication
return num * num * num
num = 5
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125
Using Exponentiation Operator
The exponentiation operator ** is a straightforward way to raise a number to any power. To find the cube, you simply raise the number to the power of 3.
# function to find cube
def cube(num):
# exponentiation operator
return num ** 3
num = 125
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125
The pow() Function
The built-in pow()
function can also be used to raise a number to a power. It takes two arguments: the base and the exponent.
# function to find cube
def cube(num):
# inbuilt pow() function
return pow(num, 3)
num = 5
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125
Lambda Function
The Lambda functions are small anonymous functions defined with the lambda
keyword. They can be useful for simple calculations.
num = 5
# lambda function find cube
cube = lambda x: x * x * x
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125
Using For Loop
To find the cube of a number using a for loop, you need to multiply the number by itself three times. This can be done by initializing a result variable to 1 and then repeatedly multiplying it by the number.
# function to find cube
def cube(num):
# product varib]able
result = 1
# for loop
for _ in range(3):
result *= num
return result
num = 5
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125
The math.pow() Function
Another way is to use pow()
function of the math module, which is used to raise a number to a power. It takes two arguments: the base and the exponent.
# import math module
import math
# function to find cube
def cube(num):
# math.pow() function
return math.pow(num, 3)
num = 5
print(f"The cube of {num} is {cube(num)}")
Output:
The cube of 5 is 125