Re: öpcaö variable refrenced before assignment

Chris Angelico rosuav at gmail.com
Wed Oct 9 10:41:57 EDT 2013


On Thu, Oct 10, 2013 at 1:20 AM,  <markotaht at gmail.com> wrote:
> def koguarv_ridu failis(f):
>     for i, l in enumerate(f):
>         pass
>     return i+1

This will throw the exception you're seeing (by the way, it helps a
LOT to actually copy and paste the full error, including the traceback
- fortunately I can work this one out without) if the enumerate()
doesn't yield any results. The whole loop gets skipped, nothing gets
assigned to i. But the real question is: why are you not getting
anything to enumerate?

> def palgad(f4):
>     palgad = 0
>     while True:
>         f4r = f4.readline()
>         if f4r == "":
>             break
>         palgad += int(f4r[f4r.find(";")+1:])
>     return palgad
>
> def kuu_keskmine(palgad, f):
>     return palgad/koguarv_ridu_failis(f)

And this would be why. Your first function is consuming the whole file
(up to a blank line, but I'm guessing your file doesn't have any), and
there's nothing left for ridu to read.

But first, a word on naming. You've used the name palgad in four distinct ways:

1) The function introduced in 'def palgad(f4)'
2) A local variable inside #1, which accumulates the returned integer
3) A local variable inside keskmine, which happens to be passed the
value that #1 returned
4) The file name, palgad.txt

This is not a problem to the interpreter, as they're quite separate,
but your first three senses are very confusing to a human.

So. You have a major problem here in that you're calculating a number
and then trying to divide it by the number of lines. There's a much
MUCH simpler, cleaner, _and_ safer way to do that: just count up the
lines at the same time as you calculate palgad. I'll let you do the
specifics, but that's what I would advise you to explore :)

Best of luck!

ChrisA



More information about the Python-list mailing list