Home > other >  I am newbie in python and a basic python code is not showing the output
I am newbie in python and a basic python code is not showing the output

Time:03-14

I want to multiply all the elements in list in python and this is my code

def mul(i):
       a=1
       for ele in i:
                   a*=ele
                   return a
       list = [1,2,3,4,5]
       print(mul(list))

But code is not working Pls tell me what mistakes i am making. And i use python 2.7.18

CodePudding user response:

Make sure you get the indentation right, Try:

def mul(i):
    a=1
    for ele in i:
        a*=ele
    return a
                   
list = [1,2,3,4,5]
print(mul(list))

Sorry, it is TL/DR, but read: Python indentation

CodePudding user response:

You are not using the correct indentations. Indentations are the empty spaces before each lines, and they tell the computer how to read your code properly.

For example,

def mul(i):
    a=1

The computer knows that a=1 is part of the multiply function because of the indentation before a=1, indicating that it belongs to the mul function.

Indentations are usually 2 spaces, 4 spaces, or a tab's spacing. Over here your indentation for

                   a*=ele
                   return a

is too far in.

The reason the code doesn't work is because

       list = [1,2,3,4,5]
       print(mul(list))

should not be part of the mul function, while the indentation suggests that it is. On top of that, the return function is indented in the for loop, meaning you are returning multiple times when you should not be.

The correct way to write this code therefore would be:

def mul(i):
    a=1
    for ele in i:
        a*=ele
   return a

list = [1,2,3,4,5]
print(mul(list))
  • Related