1

I am trying to run a while loop in Python 3 until a counter is over 10

#Set variable
option_current = 1

def myfunction(option_current):
    option_current = option_current + 1
    print ( option_current )

while ( option_current < 10 ):
    myfunction(option_current)

My counter never progresses past 2, can someone help?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

4

You're passing option_current which is defined to be 1 and everytime you call your function you're just printing option_current += 1 which is 2. It's not updating the way you think it is. They're in different namespaces. option_current = option_current + 1 is within the namespace of that function whereas option_current outside of it is global. So, your print statement inside of that function and the increment is just continuously printing and +1 ing the "local" option_current within that function and not modifying the global variable. If that makes sense.

Using global which I don't recommend.

option_current = 1

def myfunction():
    global option_current
    option_current = option_current + 1
    print ( option_current )
while ( option_current < 10 ):
    myfunction()

One way without global

def myfunction(current):
    current += 1
    print(current)
    return current

current = 1
while ( current < 10 ):
    current = myfunction(current)

Although, if this is all your function does....

current = 1
while current < 10:
    print(current)
    current += 1
Pythonista
  • 11,377
  • 2
  • 31
  • 50
0

I believe that you want the 'global' option and to remove the parameter for the function:

#Set variable
option_current = 1

def myfunction():
    global option_current
    option_current = option_current + 1
    print ( option_current )

while ( option_current < 10 ):
    myfunction()

Output:

2
3
4
5
6
7
8
9
10
slightlynybbled
  • 2,408
  • 2
  • 20
  • 38
0

everyone is suggesting global, although it is a terribly bad style.

You should count the variable up inside the loop, so your code may look like this:

option_current = 1


def myfunction(option_current):
    print(option_current)

while option_current < 10:
    myfunction(option_current)
    option_current += 1

But this can be solved even better:

def myfunction(option_current):
    print(option_current)

for option_current in range(1, 10):
    myfunction(option_current)
CodenameLambda
  • 1,486
  • 11
  • 23