beginner's python help

Chris Rebert clp2 at rebertia.com
Sun Sep 6 09:15:28 CEST 2009


On Sun, Sep 6, 2009 at 12:00 AM, Maggie<la.foma at gmail.com> wrote:
> code practice:
>
> test = open ("test.txt", "r")
> readData = test.readlines()
> #set up a sum
> sum = 0;
> for item in readData:
>        sum += int(item)
> print sum

A slightly better way to write this:

test = open("test.txt", "r")
#set up a sum
the_sum = 0 #avoid shadowing the built-in function sum()
for line in test: #iterate over the file directly instead of reading
it into a list
        the_sum += int(line)
print the_sum

> test file looks something like this:
>
> 34
> 23
> 124
> 432
> 12
>
> when i am trying to compile

No, the error is happening at runtime. Pretty much only SyntaxErrors
occur at compile-time.

> this it gives me the error: invalid
> literal for int() with base 10
>
> i know a lot of people get this and it usually means that you try to
> cast a string into an integer and this string does not really contain
> a “digit”..so I am just not sure how to correct it in this case...

I would recommend putting a `print repr(line)` inside the loop, before
the "+=" line. This will show the input int() is getting so you can
see out what the bad input is that's causing the error and thus debug
the problem.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list