Jorgesys' answer is adequate, I'm just going to add some concepts.
One of the first things about Python that should call attention to every programmer that comes from other languages, is the theme of the indentation. In most languages that have block start / end statements, the classic keys {}
of C or Java , the BEGIN/END
of Sql and etc., the indentation is usually optional, and is used simply to give readability to the code.
Python does not use logical end-of-block statements ( :
marks the beginning) since it uses indentation directly as a way to structure the logic. This at first may seem "weird", but when this concept is "internalized", it becomes totally transparent and highly effective when writing the code because:
- You have to write much less
- The way to write code is more standard
- The code is more readable
The official method to establish the indentation is to use blocks of 4 spaces, but it also works using the classic {TABS}
, the important thing is that you can not mix criteria, but we will get an execution error.
As we said, every logical block starts with the :
and what follows must be indented one level more than this, examples:
if True:
print("Es true")
def función():
pass
class Algo():
def __init()__:
pass
In your example, you have written: for word in words:
and the following statement is not one level in but is at the same level, therefore you get a IndentationError: unindent does not match any outer indentation level
. The correct form is the following:
# Este es tu ejemplo corregido
for word in words:
result += word
You also have another indent error in the return
, which will surely generate another exception when you correct the first problem.
Comment : One doubt that may arise, is if it is possible to write blocks without code, which would be a {}
in C, if possible but you have to use the clause pass
, for example:
for word in words:
pass
Only informative, with respect to the logic of your function is appropriate to what you are wanting to do / investigate, but in Python there are always more compact ways to solve a problem, the same thing you are looking for you can solve it like this:
n = ["Michael", "Lieberman"]
print("".join(n))
In this example we use the "method" join
of the class str
that directly receives an object "iterable" as a list or a dictionary and concatenates them using a "null" string, ""
as a separator.