Python Program to Generate Cube of Numbers

Welcome back to this tutorial in this article we are going to discuss how to get a cube of any given number in Python using a while loop.

This program generates all the cube numbers up to a given number n using a while loop.

Simple Code:

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

i = 1

while i**3 <= n:
    print(i**3)
    i += 1

Output:

Enter a number: 54
1
8
27

Code with Comments:

# Input
n = int(input("Enter a number: "))

# Initialize counter and result
i = 1

# Loop until cube of i is less than or equal to n
while i**3 <= n:
    # Print the cube of i
    print(i**3)
    # Increment the counter
    i += 1

Explanation:

We start by getting the input from the user, which is the upper limit n.

Then, we initialize a counter variable i to 1, which will keep track of the current number whose cube we need to calculate.

We use a while loop to repeatedly check whether the cube of i is less than or equal to n.

If it is, we print the cube of i using the expression i**3, and then increment i by 1 to move on to the next number.

This process continues until the cube of i is greater than n, at which point the loop terminates.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading