You doubt about multiplying items in a list

3

I'm doing an exercise in Codecademy, specifically this one: Modify each element of a list in a function The case, that the code that I'm trying to use is 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)

And I always get the same error:

  

File "python", line 5       x [i] = x [i] * 2       ^   IndentationError: expected an indented block

I have already tried to completely rewrite the code, I have asked in the official forums of the page and they have not been able to answer me.

    
asked by Feror 03.08.2016 в 15:07
source

1 answer

3

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>     
answered by 03.08.2016 / 15:22
source