Jordan S. - 3 years ago 152

Python Question

First time poster here (and pretty much completely new to python) with an undoubtedly easy question. I'll cut to the chase, here's my current code:

`def even(x):`

if x % 2 == 0:

even = True

else:

even = False

if even is True:

print("Even")

if even is False:

print("Odd")

N=[1,3,2,4]

for x in N:

even(x)

As it is the function takes each input and prints whether it's Even or Odd, very basic.

I gave myself the objective of writing a function/script that will take a list of numbers and spit out something like: "There are 15 even numbers and 8 odd numbers." However, I'm having trouble understanding how to count up a running total of how many times my variable "even" is True or False. Furthermore I don't understand how to then use that variable outside the function. So far my best attempts result in an output like:

There were 1 Odd numbers

There were 1 Odd numbers

There were 1 Even numbers

There were 1 Even numbers

etc... for whatever is in list N.

Whereas what I want is:

There were 2 Odd numbers

There were 2 Even numbers

Can anyone help me learn how to do something like this?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can use `sum()`

and `map()`

:

```
def even(x):
return (x % 2 == 0)
N = [1,3,2,4,6,8]
n_even = sum(map(even, N))
print(n_even)
# 4
```

Now `even`

returns `True`

(1) if the number is even and `False`

(0) otherwise. Now simply sum it up and you have the times an even number occurred.

Additionally, you might want to define `n_odd`

as

```
n_odd = len(N) - n_even
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**