Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+7 votes

For instance, you might get an ERROR message about Python not expecting and indent, or something like that. Or, your code might run, but it doesn't do what you want it to, because some line of your code isn't indented at the right level.

What's up with this?

asked in CSC201 Spring 2021 by (508 points)

2 Answers

+6 votes

Beginning Python programmers often don't realize just how important it is to think about indentation (i.e. how far indented your code is, by hitting the TAB key in Thonny, or typing four spaces, etc).

Indentation is how Python decides whether one statement is grouped "inside"/"outside" of a function, FOR loop, and other things.

Let's go through some examples using FOR loops, to help make this clear.

for i in range(5):

This code will display 5 A's, and then one B.
The print("A") statement is "inside" the FOR loop -- that is, it runs every time the loop goes.
The print("B") statement is "outside" -- that is, it just runs once, AFTER the loop is finished running.

Contrast this with:

for i in range(5):

This code will display A B A B A B A B A B (although with each letter displayed on its own line, unless we changed it to use print(...,end="") )
This is because both print statements are "inside" the loop, so they will both get run repeatedly.

Note: you must have all your indentation line up, so if you try something like this

for i in range(5):
  print("B")         #<-- bad indentation here!

then you will get an indentation error, and Python won't run your code at all, because it doesn't know whether your print statements are inside/outside, and it refuses to guess. Similarly

for i in range(5):
      print("B")         #<-- bad indentation here!

this will also cause an error.

Here's one more final more complex example:

for i in range(3):
    print("A", end=" ")
    print("B", end=" ")
    print("C", end="*")

will display A B C*A B C*A B C*D$E$F

answered by (508 points)
+2 votes

Along with the indentation, it also matters where you place the calculations. Like for example in routine practice 3, for questions 4 and 5, the calculations you want to appear after printing to repeat should be placed after for statement, not place before the for statement.

answered by (1 point)