FAQ: Code Challenge: Loops - Exponents

Makes sense, thanks mtf.

2 Likes

Hi,
It might be because I am no good at math (yet. working on it). I appreciate spoonfeeding/over-explanation if you’re so inclined as I want to make sure I truly understand what it is I am doing wrong:

#Write your function here: # My answer: def m_exponents(bases, power): new_list = [] for a in bases: for b in power: exponent = a ** b new_list.append(exponent) return new_list # Codecademy solution: def exponents(bases, powers): new_list = [] for base in bases: for power in powers: new_list.append(base ** power) return new_list #Uncomment the line below when your function is done print(m_exponents([2, 3, 4], [1, 2, 3])) print(exponents([2, 3, 4], [1, 2, 3]))

In this exersize, my code only returns the result of bases ** power, creating a list of 3 answers, while the solution creates a list that does [0] ** [0], [0] ** [1], [0] ** [2], and so forth. Creating a list that shows the whole range of exponents.

I guess I just don’t understand why. How does the solution realize it needs to do this multiple times for each base, and why does my attempt only look for the results?

Edit: You guys probably already know this, but: running the code only gives response for the latest call, so I updated so that you can easier see the comparison

Unlike some other languages (such as JavaScript), indentation is very important in Python and can change the logic of your code.
In the Codecademy solution, pay special attention to the indentation of the statements.

``````for base in bases:
for power in powers:
new_list.append(base ** power)
``````

The second loop is nested inside the first loop. The `append` statement is in the body of the second loop. So, it will be executed in every single iteration of the second loop.

``````for a in bases:
for b in power:
exponent = a ** b
new_list.append(exponent)
``````

The `exponent = a ** b` statement is in the body of the second loop, but the `append` statement is not in the body of the second loop. So, the `append` statement only gets executed in every single iteration of the first/outer loop.

If you change the indentation,

``````for a in bases:
for b in power:
exponent = a ** b
new_list.append(exponent)
``````

Now, the `append` statement is also in the body of the second/inner loop and will be executed in every single iteration of the inner loop.

1 Like

Thank you very much for the answer!

1 Like