Can't figure out what is wrong with this function, it keeps asking for indentation in the indented block, help! def sqrt(x): """Returns the square root of x, if x is a perfect square. Prints an error message and returns None otherwise""" ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x: print x, 'is not a perfect square' return None else: return ans else: print x, 'is a negative number' return None
It's impossible to troubleshoot an indentation problem without seeing the indentation. I've seen posts where people have said that if you paste your code between triple single quotes, it's formatting and indentation will be correct. Python uses the indentation of the code to decide which "block" it belongs to. A message like yours is probably because something isn't in the right block indentationwise. Those two else statements look like a great place to start looking.
If you mix tabs and returns you get that error. Also, if your nuber of tabs/spaces are not equal, so 4 on one line but 3 on the next. As a guess, I think you want to indent like this: ``` def sqrt(x): """Returns the square root of x, if x is a perfect square. Prints an error message and returns None otherwise""" ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x: print x, 'is not a perfect square' return None else: return ans else: print x, 'is a negative number' return None ``` But I could be wrong.
Oh, and I used \(\text{```}\) three of the accents above and below it to make the block stay as a block.
Its the ` at the ~ button and you have to enter a space agter the ` to have it on the screen
Join our real-time social learning platform and learn together with your friends!