-2
def countby2(aNum):
  count = 0 
  for i in range(aNum):
     count += 2 
     return count 
  return count 

myNum = countby2(4) 

I replaced the returns in the function with prints and myNum pointed to eight as I expected, but with return, myNum points to two and I do not understand why.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41

2 Answers2

1

On the very first iteration, it increments count by 2, which sets it to 2. Then it immediately returns from the function, returning the value 2, due to the return statement inside the loop. Just remove the return that's inside the loop, leaving only the return outside the loop. That way the loop will run to completion rather than returning prematurely. The correct function looks like this:

def countby2(aNum):
  count = 0 
  for i in range(aNum):
     count += 2 
  return count
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
-2

In the provided code, the variable myNum points to 2 instead of 8 because of the placement of the return statement within the for loop in the countby2 function.

Let's go through the code step by step:

The countby2 function takes an argument aNum and initializes a variable count to 0. It then enters a for loop that iterates aNum times. In this case, since aNum is 4, the loop will run 4 times. Inside the loop, the variable count is incremented by 2 in each iteration. This means that count will take the values 2, 4, 6, and 8 during the loop execution. However, the issue lies with the placement of the return statement. It is indented within the for loop, immediately after the increment operation. This means that as soon as the first iteration of the loop completes, the function will return the value of count (which is 2) and exit the loop and the function altogether. The remaining iterations of the loop are never executed because the return statement breaks out of the loop and returns the current value of count (which is 2). Therefore, when you call the countby2(4) function and assign the returned value to myNum, the function only completes one iteration of the loop, returning the value 2, which is then assigned to myNum.

If you want the function to count by 2 for the specified number of iterations and return the final value, you should move the return statement outside of the for loop, like this:

def countby2(aNum):
count = 0 
for i in range(aNum):
    count += 2 
return count

myNum = countby2(4)

cxsred
  • 16