Nora
Nora

Reputation: 15

evaluate individual numbers within an integer to determine the even count

The program I am supposed to code for asks for a user input (can be a decimal or not) and then the function is supposed to ignore any numbers after the decimal and count how many of the numbers within the integer are even numbers. So far what I have done (I don't even know if this was the best or correct way to go about the problem) is have the user input be a string, not an integer or float, then find the decimal and assign this new number to a new variable. What I'm having trouble with is looping through each individual number to determine if its even or not. It won't allow me to convert it to an integer before the loop because it says integers can't be iterated, and when i do it within the loop it also gives me an error.

digit_input=(input("Enter a number:"))

def digit_count(digit_input): 
    i = 0 
    even_count = 0
    start = digit_input.find(".", i)
    new_num=(digit_input[:start])
    while i < len(new_num):
      new=int(new_num[i])
      if new % 2 == 0:
        even_count += 1
        return even_count
      else: 
        break 
      i+=1

print(digit_count(digit_input))

What I currently have does tell me whether or not the first integer is even or not. But if, for instance, I input 222 it tells me there's only 1 even integer

***** If there's a better way to do this feel free to tell me. I am new to python and this was the only way I could think of.

Upvotes: 0

Views: 294

Answers (2)

bluesummers
bluesummers

Reputation: 12607

In a one liner you could do this

n_even_before_decimal = len(list(x for x in digit_input.split('.')[0] if int(x)%2 == 0))

This code assumes you have the number the user input, having a decimal point as a string in the digit_input variable

Explanation

The code inside the list function is just iterating over all of the characters before the '.' (denoted as [0] of the split function) converts them into ints and checks if they are even. It saves them all to a list and counts the length at the end.

Upvotes: 0

user2390182
user2390182

Reputation: 73450

Beside the fact that there are certainly faster or more elegant ways to do that, the following changes will fix your code. Don't return after the first even digit, keep counting:

while i < len(new_num):
  new = int(new_num[i])
  if new % 2 == 0:
    even_count += 1  # do not return meaningless count now!
  # do not break otherwise, keep counting
  i += 1
return even_count  # but return count after finishing counting

Consider, for instance, this one-liner:

def digit_count(digit_input):
  return sum(1 for d in s.split('.', 1)[0] if not int(d) % 2)
  # or with a little type coercing trickery and purely string ops:
  # return sum(d in '02468' for d in s.split('.', 1)[0])

Upvotes: 2

Related Questions