-1

I am novice in python. I was writing a function with flexible arguments. But it is giving only result of first argument. I need results for every argument. Please tell me how to tackle this.

def many_squares(*args):
    for ar in args:
        squares=ar**2
        return(squares)
many_squares(25,28,35)
625
simar
  • 595
  • 3
  • 12

3 Answers3

2

Try using a sum_:

def many_squares(*args):
    sum_ = 0

    for ar in args:
        sum_+=ar**2

    return sum_

many_squares(25,28,35)

EDIT: If you need every value recorded into a list, try:

def many_squares(*args):
    list_ = []

    for ar in args:
        list_.append(ar**2)

    return list_

many_squares(25,28,35)

or use list comprehension as people said.

Acc-lab
  • 194
  • 15
2

The issue isn't with *args, it's with return. Once the interpreter hits return the function exits, so you never get beyond the first iteration in the loop. You probably want to make a list of the results and return that list:

def many_squares(*args):
    out = []
    for ar in args:
        out.append(ar**2)
    return out

many_squares(25,28,35)
[625, 784, 1225]

For this particular code, it's much simpler to do it all as a list comprehension.

def many_squares(*args):
    return [ar**2 for ar in args]

You might also be interested in using yield instead of return; see this question for explanation.

vanPelt2
  • 734
  • 5
  • 15
1

List Comprehensions to the rescue

def many_squares(*args):
    return [a**2 for a in args]

Alternatively, you can use a for loop

def many_squares(*args):
    res = [0,]*len(args)
    for idx, a in enumerate(args):
        res[idx] = a**2
    return res
DBat
  • 578
  • 1
  • 11