Reputation: 73
i need to solve a task:
a function filter_list
that takes only one argument (a list of integers) and returns two values in a tuple
So i have a conceptual understanding of how that could be achieved, however when i start writing my code, i can't assign those two values to a new variable outside the function.
numbers = [1, 10, 13, 23, 34, 45, 90]
def filter_list(nums):
for e in nums:
result1 = sum(e for e in nums if e >= 13 and e <= 97)
return result1
for e in nums:
result2 = sum(e for e in nums if e>0 and e % 13 == 0)
return result2
print(result1, result2)
print(filter_list(numbers))
result_sum = filter_list(numbers)
print(result_sum)
Upvotes: 0
Views: 970
Reputation: 128
def filter_list(nums):
for e in nums:
result1 = sum(e for e in nums if e >= 13 and e <= 97)
result2 = sum(e for e in nums if e>0 and e % 13 == 0)
return (result1,result2)
numbers = [1, 10, 13, 23, 34, 45, 90]
result_sum = filter_list(numbers)
print(result_sum)
Output : (205, 13)
I have just done a small correction in your code.
A function won't execute after a return statement.
In your case the function returns the result1 and get backs to the main code.
Edit:
def filter_list(nums):
result1 = sum(e for e in nums if e >= 13 and e <= 97)
result2 = sum(e for e in nums if e>0 and e % 13 == 0)
return (result1,result2)
numbers = [1, 10, 13, 23, 34, 45, 90]
result_sum = filter_list(numbers)
print(result_sum)
Output : (205, 13)
Upvotes: 1
Reputation: 1258
def filter_list(nums):
result1 = sum(e for e in nums if 97 >= e >= 13)
result2 = sum(e for e in nums if e > 0 and e % 13 == 0)
print(result1, result2)
return result1, result2
You don't need to do a for loop
then inside it another. Also after you return
the function is exited and you can no longer do anything. So you have to store the variables then return them at once.
Upvotes: 3