0
How can I print the negative numbers from this list using for loop in python?
# I have a list of numbers I want to print only the negative numbers. I'm using for loop, and my code is below. What is missing in that code? numbers = [1, 3, -4, 5, -6] for i in numbers: if i < 0: print(numbers)
10 Respuestas
+ 6
print(i)
+ 6
You want this?
numbers = [1, 3, -4, 5, -6]
print([i for i in numbers if i < 0])
+ 3
numbers = [1, 3, -4, 5, -6]
for i in numbers:
if i < 0:
print(i)
+ 3
DN Josh, what does "did not work" mean. if you expect to get a useful help, you have to be a bit more specific.
using print(...) in a loop means that the resulting numbers are printing in different lines. if we want to get then all in one line, we could use a comprehension as mentioned by Simba . but this also prints the squared brackets.
to avoid this you can use the unpack operator:
numbers = [1, 3, -4, 5, -6]
print(*[i for i in numbers if i < 0])
but whatever we guess can be wrong, as long as DN Josh has not shared the required result as a sample with us.
+ 2
And finally, I've solved it.
Here is the full code:
numbers = [1, 3, -4, 5, -6]
for i in numbers:
if i < 0:
print (i)
Thank you everyone for your contributions. Simba ,Sumit Programmer😎😎, Obloev Komronbek I'm glad to have your individual contributions.
My output is
-4
-6
+ 1
Obloev Komronbek i understand your points. The expected output is:
-4
-6
I've tried using print (i) but couldn't get what I'm looking for. Hence the statement "did not work".
I'm a newbie in python, pardon 🙏🙏 me for my use of words.
0
Simba not working
0
Simba it did not work too
0
DN Josh ,
thanks for your response!
in this case the code from Obloev Komronbek will work fine, and also what Simba mentioned (in his first answer) should work when you replace the line in your code with his code.
0
I won't forgive this very program for given me tough time since morning. I have to retaliate by writing more similar programs.
Check out this and guess the output
numbers = [1,4,-6,7,5, -18, -9, 8, 17, -13, 47,-91]
for i in numbers:
if i < 0:
print(i)