0

Why the print of this code is 3 3 3? In the last for loop, the variable D should increase in 1 and then update the value, until the end of the loop. But it's repeating the same initial value of D. I was expecting something 3 4 5 as result.

for j in range(0,2,1):
    D = 1
    D +=1
"""D = 2"""

def calculo222(H):
    H += 1
    print(H)

for i in range(0,3,1):
    calculo222(D)
Marcelo
  • 77
  • 9

1 Answers1

1

In Python, arguments are passed by assignment, and ints are immutable, which means you can't modify an int that's passed in to a function. The easiest fix is to return it:

def calculo222(H):
    H += 1
    print(H)
    return H

D = 2
for _ in range(3):
    D = calculo222(D)

For more details, see How do I pass a variable by reference?

wjandrea
  • 28,235
  • 9
  • 60
  • 81