anderssinho anderssinho - 1 year ago 74
Python Question

Find the last element (digit) on each line and sum all that are even python 3

Hi there Stack Overflow!

I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.

The task is to:
Find the last element (digit) on each line, if there are any, and sum all
that are even.

I have started to do something like this:

result = 0
counter = 0
handle = open('httpd-access.txt')
for line in handle:
line = line.strip()
#print (line)
if line[:-1].isdigit():
digitFirst = int(line[counter].isdigit())
if digitFirst % 2 == 0:
result += digitFirst

ANSWER = result

But this code doesnt work for me, I don't get any data in result.
What is it that i'm missing? Think one problem is that I'm not going through the line element by element, just the whole line.

Here is an example of how I line in the file can look:[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867

So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. If it's even, I save it in the a variable.

Answer Source

Don't even bother with the isdigit. Go ahead and try the conversion to int and catch the exception if it fails.

result = 0
with open('httpd-access.txt') as f:
    for line in f:
            i = int(line.strip()[-1:])

            if(i % 2 == 0):
                result += i

        except ValueError:

print('result = %d' % result)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download