-4

How do I update the counter when using function in while loop? It keep gives me 2

def Main(Counter):
    Counter = Counter +1
    print (Counter)
    
A = 1
while True:
    Main (A)

Image 1

pppery
  • 3,731
  • 22
  • 33
  • 46
l zh
  • 3
  • 1
  • 1
    1) Please format your code. In Python, indentation is *essential* ... but all the indentation is lost in your post. Use the "code" icon. 2) Please do NOT post images of code or output. Copy/paste text (and use the "code" icon) instead. – paulsm4 Jul 03 '22 at 03:53

1 Answers1

2

As you are passing the same value of A each time in Main() function, it prints the same value 2. To increase the counter you need to increment it in while loop and not in function itself.

def Main(Counter):
    #Counter = Counter +1
    print (Counter)
    
A = 1
while True:
    Main(A)
    A += 1

If you want to increment the value inside the function for some reason, you can use return keyword to return the incremented value and store it in the variable.

def Main(Counter):
    Counter = Counter +1
    print (Counter)
    return Counter

A = 1
while True:
    A = Main(A)
Utpal Kumar
  • 300
  • 2
  • 13