[Tutor] a question about indentation

arildna at stud.ntnu.no arildna at stud.ntnu.no
Fri Nov 24 10:29:35 CET 2006


Hi,

I'm fairly new to python, and trying to get used to the indentation. I 
just encountered my first problem with it. I wrote the following code:

 for ord in f_ord:
        if not ordliste.has_key(ord) :       
            ordliste[ord] = {}
        for word in e_ord:
            if ordliste[ord].has_key(word) :
                ordliste[ord][word] += 1
            else :
                ordliste[ord][word] = 1

and then later realized I had to put in one more if-test at the 
beginning of the loop. In most languages I've used, this would be simple 
-- I would simply enclose lines 2-8 in curly braces and put the if-test 
in front.

When I try do it in python, however, it seems I have to do the 
indentation all over. If I just put in the if-test, and try to indent 
all of the lines one step inwards, I get the following result:

   for ord in f_ord:
        if not ord in tegn:
            if not ordliste.has_key(ord) :       
                ordliste[ord] = {}
                for word in e_ord:
                    if ordliste[ord].has_key(word) :
                        ordliste[ord][word] += 1
                        else :
                            ordliste[ord][word] = 1

which is of course not what I'm after. I want to preserve the expression 
in the outer for-loop, and just put an if-test in front.

This isn't really a problem in this case, as the expression is quite 
small, and I can quickly check the indentation line by line. But I can't 
begin to imagine what a hassle that would be if my  expression was 70 
lines and not 7.

I suppose there is a good way to do indent whole blocks like this, but I 
haven't found out what it is. Could anybody help me out?

Thanks,

Arild Næss



More information about the Tutor mailing list