English

Write a function to generate cube's of numbers over time.

Advertisements
Advertisements

Question

Write a function to generate cube's of numbers over time.

Code Writing
Advertisements

Solution

A generator can produce cubes one at a time instead of storing the entire sequence in memory.

def cubes(start, stop, step=1):
    if step == 0:
        raise ValueError("step cannot be zero")

    number = start
    if step > 0:
        while number <= stop:
            yield number ** 3
            number += step
    else:
        while number >= stop:
            yield number ** 3
            number += step


for cube in cubes(1, 5):
    print(cube)

Output:

1
8
27
64
125
shaalaa.com
  Is there an error in this question or solution?
Chapter 8: Exception Handling & Generate Functions - EXERCISE [Page 158]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 8 Exception Handling & Generate Functions
EXERCISE | Q 14. | Page 158
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×