Indent error for the practice lab predict exercise

For this code related to the predict exercise:

      # Loop over each example
      for i in range(m):   
             # Calculate f_wb (exactly how you did it in the compute_cost function above)
             z_wb = 0
             # Loop over each feature
             for j in range(n): 
                 # Add the corresponding term to z_wb
                 z_wb_ij = X[i, j] * w[j]
                 z_wb += z_wb_ij

             # Add bias term 
             z_wb += b

             # Calculate the prediction from the model
             f_wb = sigmoid(z_wb)
             # Calculate the prediction for that training example 
             p[i] = p[i] = f_wb >= 0.5 # Your code here to calculate the prediction based on f_wb

I get this indent error:

File “”, line 24
for i in range(m):
IndentationError: unexpected indent

I’ve tried a number of things to correct it, but no progress.

I think my code is correct.

Any suggestions?

Whitespace is critical in writing Python code.
Apparently some of your code earlier in that notebook cell has different indentation.

You have two different indentation styles just in the code you posted.
The first level appears to be seven spaces, the second level is four.

This is not good when you’re writing Python.

Right, I’ve been learning about how crucial it is.

Is there a fairly easy way to fix it?


It depends on the editor. I’m going by memory here, I think this works with the Coursera Labs.

Delete all of the indentation, so every line of code starts in column 1.
I think a shortcut for this is to click-and-drag all of the text, then press shift-tab a couple of times. That will remove indentation.

Then re-insert the indentation.
You can select blocks of text and indent the whole block with the tab key.

Avoid mixing spaces and tabs.

Most python editors automatically change tabs into a configurable number of spaces. Four is typical.

Got it, thanks.

I shift-tabbed all the text and removed all of the indentation.

And then I selected whole blocks and indented them with the tab key.

Still getting this error:

File “”, line 17

IndentationError: expected an indented block

If this is inside a function, the function definition starts in column 1.
So all the code within the function has to be indented

Hi @brooksjordan, @TMosh is right, you need to indent everything inside the function, starting from the Doc String.

Screenshot from 2022-07-11 12-15-11

Yep the function is

def predict(X, w, b):

All of the code within it is indented.

You need to ident the highlighted Doc String as well.

Screenshot from 2022-07-11 12-17-13

1 Like

Ohh, yes it was the Doc String!

I have learned something about indenting in Python. :grinning:

Thanks to both of you.

The whitespace rules in Python are one of its least comprehensible features (personally I prefer languages that use curly-braces).