The positive_numbers
function should return a list containing numbers that are non-negative (>=0).
However, currently, it returns only the [3]
instead of a list of values.
I tried different ways to make this work I'm currently a beginner in python and I don't have anyone to ask that's why I'm sorry if this is too basic for you just want to learn and see my mistake
def positive_numbers(numbers):
for number in numbers:
result = []
result = result + [number]
if number < 0:
continue
return result
Expected: The function should return a list of numbers
Actual: returns list with the only value being 3
Error: The call positive_numbers([1, 2, 3])
should return [1, 2, 3]
, but it returned [3]
You reset the list each iteration of the loop because of result = []
.
Try this:
def positive_numbers(numbers):
result = []
for number in numbers:
if number > 0:
result = result + [number]
return result
Also, debugging would make this very clear. Try to debug your code to get a better understanding of it.
You have to declare result
outside of your for loop.
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result.append(number)
return result
As already stated, you are setting results
no a new empty string at every iteration of your for loop. Also, the if
statement does not make any change, since by the time is evaluated, the new number is appended to the result.
So the minimal working change is:
def positive_numbers(numbers):
result = []
for number in numbers:
if number 0:
continue
result = result + [number]
return result
Besides, note that you could use a list comprehension for that:
positive_numbers = [number for number in numbers if number >= 0]
Or using filter
:
positive_numbers = list(filter(lambda num: num>=0, numbers))
Note that in the latter case, if you don't need your output to be a list but an iterable, you can remove the list(...)
part
You have all of the pieces, just not necessarily in the right order. Here is an amended version:
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result = result + [number]
return result
With result = []
inside the for loop as you had it, you were emptying the result on each iteration. Then you were unconditionally adding the number to the list instead of checking if it is negative first. In this amended first, the loop skips to the next number if the current number is not non-negative.
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
I am using triple quoted string, have if-else conditions inside the string, and defining the value of variable as per the conditions, and I am not able to use the variable outside the the string
Hello I make an app with JAVA in android studio
I have created a custom view inside which I have drawn multiple arcs of different colors
I am looking at Android's DRM documentation and I see the following diagram: