This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by maxxtheknife
almost 9 years

indenting

I tried posting this on the lesson about indenting and it wouldn’t work (maybe someone didn’t indent properly?).

On the first lesson on whitespace it says “Indent your code with four spaces” but it doesn’t say when. When do you indent? Because I tried indenting on the next lesson and it said my second line was wrong. Both lines were indented and I had to un-indent the second, but not the first. Why? Why do we indent? When? How do I know when to indent and when not to?

Answer 55559480e0a3003aec00005b

1 vote

Permalink

Say you create a function. The first line of the function would be:

def f():
    # this is inside the function
# this is outside
    # this is invalid indentation, the function has ended

You would then indent each line which belongs to the function, indentation is what says which lines belong in the function.

If you put a loop in the function, you would further indent the lines belonging to the loop:

def f():
    for c in 'hello':
        # inside the loop which is inside the function
    # inside function only
# inside neither

Other languages commonly use { and } to signify these blocks, and typically indent as well. In Python we consider this unnecessary clutter.. Well, there are opinions both ways of course, some more strong than others.

points
Submitted by Jonatan
almost 9 years