0

I have started learning python.

I don't know how to pass values for function?

Here is the code:

def summation(*numbers):
    add = 0
    for y in numbers:
        add = add + y
    return add


n = int(input("How many numbers you want to add: "))
for x in range(1, n + 1):
    int(input("Enter number: "))
print("Sum:", summation())

print("Sum:", summation()) How can I pass for summation?

4 Answers4

1
def summation(numbers):
    add = 0
    for y in numbers:
        add = add + y
    return add


n = int(input("How many numbers you want to add: "))
row_nums = []
for x in range(1, n + 1):
    row_nums.append(int(input("Enter number: ")))
print("Sum:", summation(row_nums))

I just did a quick tweak to your code. Also, you have to store your numbers while reading them.

I put a variable when declaring the function without choosing its type. and use it in my code as a list. Python is not a strongly typed language.

Skander HR
  • 580
  • 3
  • 14
1

As you were told in comment, it is enough to store the numbers in a list. The you can pass the values of the list by prefixing it with a *:

n = int(input("How many numbers you want to add: "))
# the pythonic way to build a list is a comprehension:
numbers = [int(input("Enter number: ")) for x in range(n)]
print("Sum:", summation(*numbers))
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You could just turn the way you get the numbers into a generator:

In [2]: def numbers(): 
   ...:     n = int(input("How many numbers you want to add: ")) 
   ...:     for x in range(1, n + 1): 
   ...:         yield int(input("Enter number: ")) 

In [4]: print("Sum:", summation(*numbers()))                                                                                  
How many numbers you want to add: 3
Enter number: 1
Enter number: 2
Enter number: 3
Sum: 6
phipsgabler
  • 20,535
  • 4
  • 40
  • 60
0

What you are looking for are variable arguments for a function:

def summation(*args):   # notice how the asterisk 
                        #   is used to signify variable arguments
    sum = 0
    for y in args:
        sum = sum + y
        # sum += y
    # Or simply
    # return sum(args)
    return sum

n = int(input("How many numbers you want to add: "))

# We will record users input in this set
numbers = set() 

for x in range(1, n + 1):
    # Here we keep a record of users input
    numbers.add(int(input("Enter number: "))) 

print("Sum:", summation(*numbers)) # Finally we pass 
                                   #  in the whole set tot he function

Notice how the asterisk is used to pack and unpack a tuple.

If you'd like to learn more about the concept, you can google for the keywords above or start from this excellent article.

Mayank Raj
  • 1,574
  • 11
  • 13