Write A Python Function To Return The Cube Of A Number

Give an integer value as an input to the program your task is to to write a function that  calculates the cube of a number and then returns the result.

There are two ways to solve this,  Python supports double star operators to raise a number to the power of n.  

For example suppose you want to raise 5 ^ 2 you can use 5 ** 2  in Python to get the 5 square

If you need 5 cube then you have to to use 5 ** 3 in Python to get the cube of 5.

 

 

Write A Python Function To Return The Cube Of A Number



Write A Python Function To Return The Cube Of A Number

Let's define a function named cube and pass the input argument as integer value n,  now using the return keyword  raise the value of n ^ 3 this will give us the cube of a number,  return this value.

def cube(n):
   return n ** 3




In the main program let's take a variable number and using the input function ask a user to enter a number. Convert the number into an integer from string to int type conversion.

Using the print function call, print the cube of the number directly calling inside the print function call as shown below.

number = int(input("Enter a Number : "))
print(f"Cube of {number} is {cube(number)}")



Complete program
======================

def cube(n):
   return n ** 3


number = int(input("Enter a Number : "))
print(f"Cube of {number} is {cube(number)}")



Output
==================

Enter a Number : 100
Cube of 100 is 1000000



Output 2
====================

Enter a Number : 3
Cube of 3 is 27




Calculating the cube of a number using multiplication operator

We can also use the arithmetic multiplication operator,  changing the code in the function instead of using the double star operator to multiplication operator.

That is by using n * n * n  instead of n ** 3

Complete program
==================

def cube(n):
   return n * n * n


number = int(input("Enter a Number : "))
print(f"Cube of {number} is {cube(number)}")





Output
================

Enter a Number : 34
Cube of 34 is 39304




Output 2
===================

Enter a Number : 45
Cube of 45 is 91125




Conclusion
=================

These are the two methods to find the cube of a number,  run the program by providing the random values as an input to the  program.

Comment down below if you have any queries or concerns




Post a Comment

0 Comments