Miguel Hernandez
asked on
function adding numbers from a list in Python 3.6
Hi, this is my code:
def sumanu(numeros):
sumat+=numero
numeros=[]
for numero in numeros:
return sumat
#This code generates an error once I type the argument inside the function.
def sumanu(numeros):
sumat+=numero
numeros=[]
for numero in numeros:
return sumat
#This code generates an error once I type the argument inside the function.
Are you trying to implement the built-in function sum in module builtins?
Here's a guess as to what you are trying to do:
Here's a guess as to what you are trying to do:
def sumanu(numeros):
sumat = 0
for numero in numeros:
sumat += numero
return sumat
x = [1, 3, 5, 7, 9]
print(sumanu(x))
To add, when using numeros=[], you reuse the name numeros for another purpose. In other words, you throw away what you passed via the argument of that name, and you assign the variable the empty list. This way, you always get zero.
ASKER
Flabio: your answer does not return any error. However it only takes into account one argument. So if I type x=[2,5,7]
it only returns "2".
This function is intended to add all numbers from a given list. I would prefer to type the numbers directly into the funtion instead of assigning them to a variable, but not sure if it is possible, For example once I call the function, sumanu(2,5,7) it could return the answer: "14".
it only returns "2".
This function is intended to add all numbers from a given list. I would prefer to type the numbers directly into the funtion instead of assigning them to a variable, but not sure if it is possible, For example once I call the function, sumanu(2,5,7) it could return the answer: "14".
You have to keep return sumat exactly below the for (the same indentation. You probably have it indented the same way like sumat += numero. This way it returns immediately after the first addition, and both the loop and the function are exited prematurely.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In other programming languages, indentation is just a guide. Python requires proper indentation.
ASKER
Again thanks!
I just had to indent one more space "sumat+=numero" than you suggested. If "sumat+=numero" goes exactly below "ro" from the previous line, works perfect!
I just had to indent one more space "sumat+=numero" than you suggested. If "sumat+=numero" goes exactly below "ro" from the previous line, works perfect!
had to indent one more space "sumat+=numero" than you suggestedAre you mixing spaces and tabs? You should not! I recommend using 4 spaces as a standard.
What are you trying to do?