Level 2: Intermediate Beginner
print("The sum of the numbers is: " + str(calculate_sum(numbers_list)))
Correct!
def sum_list(n):
total = 0
for i in n:
total += i
return total
n = list(map(int, input("Enter numbers separated by commas: ").split(",")))
print("The sum is", str(sum_list(n)))
you need to convert the result of the function into a string:
You cannot concatenate a string with an integer in Python.
Change last line to::
That would fix it! 👍
Another (good) alternative would be to use an f-string and avoid using "+".
Not sure. But since the function returns an integer we need to change the type of what was returned to string?
Yes, using an str() function.
Because you use “+” sign on print function instead of “,”
"+" can also be used inside a print() function, but "," would also be a nice hack here. Best would be to use an f-string.
def cal_sum(my_list):
sum = 0
for items in my_list:
sum = sum + items
return sum
my_list = [10,20,30]
total_sum = cal_sum(my_list)
print(f"total sum of list integers is {total_sum})
The error is caused by trying to concatenate a string with an integer. The 'calculate_sum(numbers_list)' function returns an integer.
Solution: print("The sum of the numbers is: " + str(calculate_sum(numbers_list))) or
use an f-string
print(f"The sum of the numbers is: {calculate_sum(numbers_list)}")
print("The sum of the numbers is: " + str(calculate_sum(numbers_list)))
Correct!
def sum_list(n):
total = 0
for i in n:
total += i
return total
n = list(map(int, input("Enter numbers separated by commas: ").split(",")))
print("The sum is", str(sum_list(n)))
you need to convert the result of the function into a string:
print("The sum of the numbers is: " + str(calculate_sum(numbers_list)))
You cannot concatenate a string with an integer in Python.
Change last line to::
print("The sum of the numbers is: " + str(calculate_sum(numbers_list)))
That would fix it! 👍
Another (good) alternative would be to use an f-string and avoid using "+".
Not sure. But since the function returns an integer we need to change the type of what was returned to string?
Yes, using an str() function.
Because you use “+” sign on print function instead of “,”
"+" can also be used inside a print() function, but "," would also be a nice hack here. Best would be to use an f-string.
def cal_sum(my_list):
sum = 0
for items in my_list:
sum = sum + items
return sum
my_list = [10,20,30]
total_sum = cal_sum(my_list)
print(f"total sum of list integers is {total_sum})
The error is caused by trying to concatenate a string with an integer. The 'calculate_sum(numbers_list)' function returns an integer.
Solution: print("The sum of the numbers is: " + str(calculate_sum(numbers_list))) or
use an f-string
print(f"The sum of the numbers is: {calculate_sum(numbers_list)}")