0

I am a programming beginner and I was experimenting a bit with functions. I have two variables (integer) and a self-created function that adds 1 to the variable. I wanted to run the function in a while loop in which the function should keep adding 1 to the variables until one of them has reached a certain number, but it ends in an endless loop that only uses the functions once. What is my mistake?

aa = 2
bb = 5

def test(aa, bb):
    aa = aa + 1
    bb = bb + 1
    return aa, bb

while aa < 6:
    test(aa, bb)

print(aa, bb)
Ironkey
  • 2,568
  • 1
  • 8
  • 30
funwide
  • 25
  • 4
  • 1
    The issue is that `aa` and `bb` as passed by value (not reference) and the parameter names mask the global scope defined variables. – Tibebes. M Oct 24 '20 at 19:34

1 Answers1

2

Assign returned variables from test() to aa and bb:

aa = 2
bb = 5

def test(aa, bb) :
    aa = aa + 1
    bb = bb + 1
    return aa, bb

while aa < 6 :
    aa, bb = test (aa, bb)  # <-- assign returned variables to aa, bb

print (aa, bb)

Prints:

6 9
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 2
    Just in case the confusion is stemming from a misunderstanding of scope: this is necessary because the `aa` in `test` is not the same `aa` defined at the top. `aa = aa + 1` is changing the parameter, but that doesn't change the data that was passed in, or the global `aa`. – Carcigenicate Oct 24 '20 at 19:33