Find the last element (digit) on each line and sum all that are even python 3
<p>Hi there Stack Overflow!</p>

<p>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.</p>

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

<p>I have started to do something like this:</p>

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


    ANSWER = result
</code></pre>

<p>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.</p>

<p>Here is an example of how I line in the file can look:</p>

<pre><code>37.58.100.166--[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
</code></pre>

<p>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.</p>

<pre><code>result = []
with open('https-access.txt') as fin:
    for line in fin:
        l = line.strip()
        if l[-1].isdigit():
            if int(l[-1]) % 2 == 0:
                result.append(int(l[-1]))
ANSWER = sum(result)
</code></pre>

<p>How does your file look? You want to calculate the last digit on each line if it's even number. In your code "line[counter]" will catch the first index of each line.</p>

<p>For example if data in file is as follows:</p>

<pre><code>some_data 2
</code></pre>

<p>since counter is set to 0, therefore line['counter'] in your code will always check the first index which will be 's' in the example above.</p>

<p>If you can post a few lines from the file that you will be opening, I may be able to suggest something.</p>

python python-3.x