Python recognizes the blocks of code by their level of indentation, in fact, the same interpreter tells you the error IndentationError
on line 5.
As you currently have the code, I doubt it will be executed, since after each :
when writing a sentence, Python expects a different indentation level than the one that contains the line with :
, I explain:
This is your current code:
n = [3, 5, 7]
def doble_lista(x):
for i in range(0, len(x)):
x[i]=x[i]*2
return x
print doble_lista(n)
Indented would finally look like this:
n = [3, 5, 7]
def doble_lista(x):
for i in range(0, len(x)):
x[i]=x[i]*2
return x
print doble_lista(n)
This last one works well.
Going a little deeper, why is this happening? As I said earlier, Python recognizes indentation levels as blocks of code, example:
def DiHola():
print "Hola"
It does not work as we expect, because the definition of the method DiHola()
is at the same level as the print
, the correct thing is to indentate even for a space, to define the block of code:
def DiHola():
print "Hola"
So, the more blocks we have, we have to indentate:
def EjecutaAlgo():
nombre = "NaCl" # Todas las lineas que no aplican un bloque de indentado
for s in nombre: # van al mismo nivel, ejemplo estas dos.
print s
And so on, all this is in the Python programming guides PEP .
p>