In my code, i want to only count the positive numbers from a user input and print it. So far i can print only the positive numbers but i couldn't print how many positive numbers there are
my code:
num = map(float, input().split())
for post in num:
if post > 0:
print(int(post))
input:
2 -4 3.6 1
Output:
2
3
1
the output i want:
3 (the number of positive numbers)(regardless of decimals)
any advice? I've tried getting the length of 'post' but it returns an error.
CodePudding user response:
You can just use the following code.
print(len([i for i in num if i > 0]))
How it works
The above method uses list comprehension, which is equivalent to:
result = []
for i in num:
if i > 0:
result.append(i)
print(len(result))
The list result
that we get is the list of positive numbers.
>>> print(result)
[2, 3.6, 1]
And then we will use len
to count the number of elements in the list.