What is the problem with printing following code?


#1

I wrote following code, but only 6 is printed. What is the problem?

n = [3, 5, 7]

def double_list(x):
    for i in range(0,len(x)):
        x[i] = x[i] * 2
        return x[i]


print double_list(n)

#2

the function ends the moment a return keyword is reached, which in your case happens in the first run of the loop

Try changing the indention so the whole loop can run


#3

Thanks,
I tried following too:
n = [3, 5, 7]

def double_list(x):
for i in range(0,len(x)):
x[i] = x[i] * 2
return x[i]

print double_list(n)

it returns last number 14. if it is in the place as first one, it returns 6. So, it will return first or last number and I cannot have 3 numbers! what is the problem?


#4

x contains the whole list, you should return x.


#5

That's right.
Thanks.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.