Indentation is a big part of writing Python code, and it is a good thing in my opinion because it makes you write better and cleaner code. indentation is used to place code more to the right. so instead of writing your code like below;
#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"
you have to write your code using indentations to make it work in python. Meaning a functioning code will look like this;
#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"
As you can see it will make your code more readable because you can see what is inside a while look and what not. This is directly the reason why it is used in Python coding, not to make your code look nice, it has a functional part to it. In some languages you indicate the begin and end of a codeblock like a while loop with brackets, a { to start and a } to end the while block. In python you use indentations. If you do not make sure your indentation is correct you will most likely end with a " IndentationError: expected an indented block" error. Lucky for you a line number will be given so you can debug your code quickly.
Personaly I think that the use of indentation for codeblocks is great. It will learn you to write your code in a way that it is more readable for other developers. That is at least on this part. I remember re-writing code from other developers and first making sure all the indentation is correct so it becomes more readable, in in python that is no longer needed because if you have your indentation not set correct in your code you will not be able to run it in the first place. Meaning that, if your process is correct, no developer can commit code into production if the indentation is incorrect. That is to say, for the parts where it is needed.
Final word, indentation in Python code,….. a good thing.
3 comments:
Indentation is no doubt a good thing in Python but i was surprised to see that it won't let us run our code if the indentation is not correct. also, it would have been far better if the indentation was taken care of by default so that we don't have to indent our code manually.
Well to be honest I was also surprised the first time and I do tend to think in first instance that you are correct that this should not hold you back from running the code however,.... it forces you to code correctly and provide clean code and that is a good thing in my opinion.
Honestly I'm not a fan of Python's indentation usage. Sure, it forces you to indent and make things readable, but sometimes the spaces don't align right, or you want to use whitespace for organization in a different way Python accepts it. I'd much prefer using {} for blocks. But to each is own.
Post a Comment