How to pass values for a function in python?

Question:

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?

Asked By: user13899130

||

Answers:

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.

Answered By: Skander HR

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
Answered By: phipsgabler

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.

Answered By: Mayank Raj

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))
Answered By: Serge Ballesta
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.