Using a for loop to create cube integers

Viewed 426

I included problem #1 for context but I need help with problem #2:

Problem #1: Write a for loop to cube integers from 11 to 15, inclusive (i.e. including 11 and 15). You can include a print statement in your for loop to check your work.

Hint: The output should be: 1331, 1728, 2197, 2774, 3375

numbers_to_cube = [11, 12, 13, 14, 15]

for number in numbers_to_cube:

  print(number**3)

Problem #2: Now, let's combine the above for loop with creating a list of numbers. Use a list inside the for loop to hold the results; name your list cubed.

cubed = []

for number in numbers_to_cube:

  cubed.append(number**3)

  print(cubed)

The result turns out like this:

[1331]
[1331, 1728]
[1331, 1728, 2197]
[1331, 1728, 2197, 2744]
[1331, 1728, 2197, 2744, 3375]

How do I get just the very last set of numbers?

1 Answers

To get the very last set, move the print(cubed) part outside of the for-loop.

cubed = []

for number in numbers_to_cube:

  cubed.append(number**3)

print(cubed) # Prints [1331, 1728, 2197, 2744, 3375]
Related