Jordan S.
Jordan S.

Reputation: 70

Counting and Running Totals in Python 3

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?

Upvotes: 2

Views: 97

Answers (2)

Mureinik
Mureinik

Reputation: 311978

You could use a Counter:

from collections import Counter
c = Counter(x % 2 == 0 for x in lst)
print "There are %d even numbers and %d odd numbers" % (c[True], c[False])

Upvotes: 1

Jan
Jan

Reputation: 43169

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

Upvotes: 0

Related Questions