Python Control Flow - Sum of list elements upto Invalid element
I am to write a function - list_sum(numbers, n)
which takes a list of values and an integer as parameters. This function should return the sum of n
integers in the list where n
defines the number of integers required.
Note - We can assume that the list is not empty and the integer is valid (i.e. n
is less than the size of the list).
If the list contains any invalid values, the function should terminate the calculation and returns the cumulative sum up to but excluding the invalid value.
Note: It is necessary to use the try... except
syntax in the solution. For example, the following code fragment:
my_list = [1, 2, 3, 4, 'NA', 2]
print(list_sum(my_list, 5))
prints
10
The function returns the sum of the first four integers only.
E.g.:
my_list = [1, 2, 3, 4, -2, 2]
print(list_sum(my_list, 4))
Output - 10
my_list = [1, 2, 3, 4, "NA", 2]
print(list_sum(my_list, 6))
Output - 10
I have written a code but that includes characters after the invalid element too. How can I solve this issue?
My code:
def list_sum(numbers,n):
res = 0
for i in range(n):
try:
res += numbers[i]
except (TypeError, ValueError):
pass
return res
Simply replace the pass
in the except
block with return res
, as the return
statement would terminate the calculation and return the cumulative sum up to but excluding the invalid value. :
def list_sum(numbers, n):
res = 0
for i in range(n):
try:
res += numbers[i]
except (TypeError, ValueError):
return res
return res
my_list = [1, 2, 3, 4, -2, 2]
print(list_sum(my_list, 4))
my_list = [1, 2, 3, 4, "NA", 2]
print(list_sum(my_list, 6))
Output:
10
10