3

So I'm trying to figure out how to print numbers that have more even digits than odd digits. This is my code:

inVal=(input("Please enter a positive integer: "))
evencounter=0
oddcounter=0

for i in range(1,int(inVal)):
    for j in range (1,len(str(i))):
        if(int(str(i)[j])%2==0):
            evencounter+=1
        else:
            oddcounter+=1
    if(evencounter>oddcounter):
        print(i)

What's wrong?

Ravi Patil
  • 127
  • 2
  • 16

3 Answers3

3

I think that the problem is, you haven't reset your counter variables. Another problem is that your second loop starts from 1 instead of 0. (thanks Leonardo Gazdek for pointing out!)

Strings indexes start from 0:

>>> 'abc'[1]
'b'

Here's how you should do it:

inVal=(input("Please enter a positive integer: "))
evencounter=0
oddcounter=0

for i in range(1,int(inVal)):
    # add those pieces of code:
    evencounter=0 
    oddcounter=0
    for j in range (0,len(str(i))): # start from 0
        if(int(str(i)[j])%2==0):
            evencounter+=1
        else:
            oddcounter+=1
    if(evencounter>oddcounter):
        print(i)
kiyah
  • 1,502
  • 2
  • 18
  • 27
3

As zeet correctly pointed out, you need to reset the counters on each number (they don't even need to be global), but you have another issue. You need to start the second loop from 0, not 1. String indexes start from 0.

inVal=(input("Please enter a positive integer: "))

for i in range(1,int(inVal)):
    evencounter=0 
    oddcounter=0
    for j in range (0,len(str(i))):
        if(int(str(i)[j])%2==0):
            evencounter+=1
        else:
            oddcounter+=1
    if(evencounter>oddcounter):
        print(i)
Leonardo G
  • 96
  • 7
1

range(start, stop[, step]) gives values from start till values less than stop.

In your inner loop, change

for j in range (1,len(str(i))):

to

for j in range (0,len(str(i))):

since the indexing starts from 0.

And you need to reset the value of the counter after each iteration of the outer loop so that it can start over for the next number.

Also, if you want to include inVal as well, change the outer loop to

for i in range(1,int(inVal)+1):

You might also want to check this out for exception handling in case the user's input is not a number.

evencounter=0
oddcounter=0

try:
    for i in range(1,int(inVal)+1):
        for j in range (0,len(str(i))):
            if(int(str(i)[j])%2==0):
                evencounter+=1
            else:
                oddcounter+=1
        if(evencounter>oddcounter):
            print(i)

        oddcounter = evencounter = 0
except ValueError:
    print('Conversion error!')
J...S
  • 5,079
  • 1
  • 20
  • 35