简体   繁体   中英

how to acess return the for loop value from one function to other function pythin3?

I have a function named SumofSquares internally I am calling Square function passing list values.I want to iterate in Square Function and send back each for loop data into SumofSquares Please suggests me some way

def Square(Array): 
    for  data in Array:
         return data

 
def SumofSquares(Array):
   SquaredValue = Square(Array)
   
Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
Total = SumofSquares(Array)

Your original question had the yield (spelled wrong) but you removed it for some reason. You need the yield and it needs to return a value:

def square(array): 
    for data in array:
        yield data * data
 
def sum_of_squares(array):
    return sum(square(array))
  
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
total = sum_of_squares(array)

But the way you are doing things, you don't need the generator at all.

def sum_of_squares(array):
    return sum(x * x for x in array)

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
total = sum_of_squares(array)

Both examples produce the same result.

Note, I changed some names to be more in line with Python naming conventions .

Just return a list including the results you want to return:

def Square(Array): 
    res = []
    for  data in Array:
         res.append(pow(data, 2))
    return (res)

def SumofSquares(Array):
    res = 0
    for k in Array:
        res += k
    return (res)

Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
Total = SumofSquares(Array)

I also added the pow(data, 2) in your Square function (similar to data**2), because it seemed like you forgot it in your problem, feel free to remove it if I misunderstood

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM