If you're not at least marginally interested in coding, this blog post will be completely boring for you, trust me!
I'm completely new to Python but not to programming in various languages.
What I find very hard to adapt to is the special meaning Python associates with indenting, like blocks of code in other languages.
The indenting makes sense in conditional statements, loops, functions and probably more I haven't explored yet.
The solution Python has for blocks of code makes it easier to read because it enforces a certain style, but it also seems very inflexible to someone who isn't used to it.
Let's give you some examples:
This code works
a = 5
print(a)
while the following one doesn't:
a = 5
print(a)
Python interpreter complains about the potentially accidental space in front of print
greeting us with an IndentationError
. Easy fix though: you just remove the space.
How about this piece of code? What do you think, does it work?
if a > 0:
print(a)
If you answered no, you are right. You either indent it (with exactly 4 spaces), like this:
if a > 0:
print(a)
or since you only have one function call or operation, you can put it like this:
if a > 0: print(a)
Let's move to another situation, a little more complex to a beginner in Python. Let's say you want to write an if statement on two rows instead of one. For longer conditions it makes sense, in our case it's just an example, normally it would be all on one line. If you write it like this
if a > 0 and
a < 10:
print(a)
you get a SyntaxError
error pointing at the and
. Any idea what that means? It's less obvious than an IndentationError
already.
So, what is wrong with that statement is that we missed a \
at the end of the line containing the error. When you break a line of code in Python because it's too long or because you want to format it in a certain way, you need that character at the end of each line, until the end of the statement, in our case the column (:
).
Funny thing is that when you break a line, the following lines don't respect the indentation rules, so something like this is perfectly fine for the interpreter:
if a > 0 and \
a < 10:
print(a)
Until now all we had were easy to fix errors the interpreter catches and let us know about them. The problem is when you have logic errors, they are harder to track down and fix.
Here's one example, again focusing on how indenting works in Python.
i = 0
while i < 10:
print(i)
i = i + 1
Any idea how this piece of code will work? How do you fix it?
Hint: it has something to do with indenting...
I see more potential disruptions due to indenting. For example in a code of a function with hundred of lines, accidentally unindenting a "block" within another "block", if it doesn't make the whole thing crash with errors, will completely change the logic of the code. And that through a simple backspace.
On this particular aspect, I still prefer traditional blocks, with parenthesis or even keywords.
But Python is still worth exploring further.