Skip to main content

calculate cube of numbers in python using while, for loop

Here is simple three line program to calculate cube and print it as per user input or range using while loop

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

i = 1;
while i <= rangeNo:
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))
    i=i+1

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000

Below program is to calculate cube of numbers using for loop up to number (user input)

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

j = 1;
for i in range(j,rangeNo+1):
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000