>>>Python_indentation == "__Can drive you crazy in the beginning__!"
My Python journey began exactly a month ago, and nothing about it drove me crazy like it indentation. My sole source of learning the language was the Python 101 book by Michael Driscoll.
Well, the Python 101 book did a very good job at telling me indentation was important but what I didn’t get was why and what will happen if I didn’t indent. I mean when I was learning Java and JavaScript, there were numerous books that said indentation was a good practice. So I told myself when I was writing my python code that my code will still run even if I didn’t indent.
That thought and carelessness of knowledge acquisition became my worst nightmare as I found myself spending over eight hours trying to figure out why my code wasn’t running.
The syntax error below became my worse nightmare with it recurrence:
SyntaxError: unindent does not match any outer indentation level
After series of youtube videos and stack Overflow
, I finally came to understand the relevance of the Python indentation, which I low-key started to refer to as Python curly bracket -{}
. The relevance and significance of the indentation in Python is due to the absence of curly bracket in the language. Unlike other programming languages that use curly braces to show the context or inclusion of lines of codes, python uses indentation.
The code above results into the syntax error below:
So why is the code not running? its simple, after the if-statement
, Python was expecting a line of code to end it but all it found was a print-statement
, which occurs on the same line as the if-statement
, making it independent of the if-statement
and confusing the python shell
which knows or assumes the print-statement
should belong to the context of the if-statement
.
How do we solve this? we make the print-statement dependent on the if-statement by making it occur on a column(col) greater than it:
Note: a column increase leads to a shift to the right of a character’s position.
col "if-statement" == 0
col "print-statement" == 4
so now the code will run because the print-statement has been made dependent on the if-statement.
The indentation(col) of the print-statement could have been anything aside zero as zero will make it independent or out of the context of the if-statement. The 4-length indentation is the most popular length used by Python programmers.
Also: because I started my code with an indentation of length-4
, I need to maintain the same length across the current Python module. indent.py
To exit the if-statement
, I will move back to the column 0 of whichever line I am currently on or prefer to be(i.e Ln:x col:0).
I would not have faced the problem of indentation if Python were to be my first programming language because then I would not have taken indentation for granted. Before you start learning Python, bare in mind that indentation is_part of_the code_itself
.