Sum of cubes. Given an integer N, calculate the sum of cubes of all integers from 1 to N:
|
# Read the input value for N N = int(input()) # Initialize the total sum to 0 total_sum = 0 # Calculate the sum of cubes from 1 to N for i in range(1, N + 1): total_sum += i**3 # Print the total sum print(total_sum) |
- Reading Input:
- The
input()
function reads a line of text from the user.
- The
int()
function converts this input to an integer and stores it in the variable N
.
- Initialize the Total Sum:
- A variable
total_sum
is initialized to 0. This will be used to store the sum of the cubes of integers from 1 to N.
- Calculate Sum of Cubes:
for i in range(1, N + 1):
total_sum += i**3
- A
for
loop iterates over the range from 1 to N (inclusive).
- In each iteration,
i**3
(the cube of the current number i
) is added to total_sum
.
- Print the Total Sum:
- Finally, the
print()
function outputs the value of total_sum
.