Link to home
Start Free TrialLog in
Avatar of Miguel Hernandez
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.
Avatar of Flabio Gates
Flabio Gates

Lots of things wrong here.

  • sumat has not been assigned a value hence you cannot execute the line "sumat+=numero"
  • you redefine the argument numeros with the line "numeros=[]" -- the indentation is crucial in python
  • same with your for loop -- due to indentation, it is part of the definition of the function sumanu

What are you trying to do?
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:
def sumanu(numeros):
    sumat = 0
    for numero in numeros:
        sumat += numero

    return sumat

x = [1, 3, 5, 7, 9]
print(sumanu(x))

Open in new window

Avatar of pepr
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.
Avatar of Miguel Hernandez

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".
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
Avatar of Flabio Gates
Flabio Gates

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In other programming languages, indentation is just a guide. Python requires proper indentation.
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!
had to indent one more space "sumat+=numero" than you suggested
Are you mixing spaces and tabs? You should not! I recommend using 4 spaces as a standard.