Skip to content
Advertisement

Why my function (f(x)=x*2) doesn’t returns anything?

I know that there are way simpler ways to calculate the square of a number and store it in an array, but for the sake of another problem. I need to understand why nothing happens in this code and its structure (is the return(a) necessary ?):

s=[1,2,3,4,5]


def square(x):
    return x*x
    def iterate(b):
        sol=[]
        for b in s:
            a=square(b)
            return(a)
            sol.append(a)
        print(sol)

The goal is to store the square in sol : sol = [1,4,9,16,25]. But the code runs without printing anything. What make the following code work and not the previous one ?

s=[1,2,3,4,5]

def square(x):
    return x*x
    
     
sol=[]
for b in s:
    a=square(b)
    sol.append(a)
print(sol)

(My problem involves curve fitting, and this structure doesnt fit my needs)

Advertisement

Answer

The problem is that you define iterate within square but you never call iterate. It would be better to have iterate be a separate function that calls square:

values = [1,2,3,4,5]  # do not call your variable set - it is a Python keyword

def square(x):
    return x*x



def iterate(values):
    
    solution = []
    
    for value in values:
        value_squared = square(value)
        solution.append(value_squared)
    
    return solution

You could also do this without defining iterate using a list comprehension:

[square(value) for value in values]

Edit:

To answer your other questions, here is your code:

s=[1,2,3,4,5]


def square(x):
    return x*x
    def iterate(b):
        sol=[]
        for b in s:
            a=square(b)
            return(a)
            sol.append(a)
        print(sol)

In square, you never call iterate so this part of the code never runs.

If you add a call to iterate within square, you will end up in an infinite loop. This is because within iterate you call square, but you always iterate over your list s. This means that inside iterate, square(b) will always be square(1).

Within iterate you use the global variable s but it would be better to restructure your code so that you take s as input.

If you are learning about inner functions, you could define iterate and within this define square:

values = [1,2,3,4,5]


def iterate(values):

    def _square(x):
        return x*x
    
    solution = []
    
    for value in values:
        value_squared = _square(value)
        solution.append(value_squared)
    
    return solution
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement