Reputation:
I am trying to make a program that will sum the cube of a number up to an upper boundary.
The mathematical formula is (n*(n+1)/2)^2
My code in Python:
def cube_numbers():
upper_boundary = 0
cube_sum = 0
upper_boundary = input("Please enter the upper boundary:")
cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2)
print("The sum of the cube of numbers up to" & upper_boundary & "is" & cube_sum)
#main
cube_numbers()
But I get the following error:
Traceback (most recent call last):
File "C:/Users/barki/Desktop/sum of cubes.py", line 10, in <module>
cube_numbers()
File "C:/Users/barki/Desktop/sum of cubes.py", line 5, in cube_numbers
cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2)
TypeError: can only concatenate str (not "int") to str
Upvotes: 1
Views: 1220
Reputation: 115
print("The sum of the cube of numbers up to" & upper_boundary & "is" & cube_sum)
You should format your code properly, either by using .format
notation or separating different values by ,
or conacatinating them by converting integer type values to string using str
(not recommended)
Always use the .format
notation for formatting.
example,
print("The sum of the cube of numbers up to {} is {}".format(upper_boundary, cube_sum))
You can also use indexing for formatting:
example,
print("The sum of the cube of numbers up to {0} is {1}".format(upper_boundary, cube_sum))
In this case whatever is at the first place inside the format method will take the "0th" place in the string.
Another way to do this is by actually supplying some names as the placeholder:
example,
print("The sum of the cube of numbers up to {upper_bnd} is {cube_sm}".format(upper_bnd = upper_boundary, cube_sm = cube_sum))
Hope this helps.
Upvotes: 0
Reputation: 4606
The purpose of your function should not be to print
. Also it would be better to move your input
prompt out of your function and then pass that value into your function. What we can do then is get the input for upper_boundary
as an int
and then pass that to cube_numbers
. That return value will now be cube_sum
and we can use formatted printing to print out the statment.
def cube_numbers(x):
y = int(((x * (x + 1) / 2)**2))
return y
upper_boundary = int(input("Please enter the upper boundary: "))
cube_sum = cube_numbers(upper_boundary)
print('The sum of the cube of numbers up to {} is {}.'.format(upper_boundary, cube_sum))
# The sum of the cube of numbers up to 10 is 3025.
Upvotes: 3