Let me ask you a Python function. Repeat plus(a) to increase the value of a.

Asked 2 years ago, Updated 2 years ago, 14 views

count=0

def plus(a):

    a=a+1
    print(a)

for i in range(3):

    plus(count)

If you run it like this, 1,1,1 appears.

How do I make it 1,2,3?

python

2022-09-20 22:00

1 Answers

The reason why 1 comes out 3 times...

count=0

def plus(a): # <-- (2) plus(0) executed
    a=a+1 # --> (3) only variable a in plus() is changing, and count is unchanged
    print(a) # --> (4) 1 Output

plus(count) # --> (1) at this point count = 0
plus(count) # --> (5) Count has never changed at this point, so count = 0, 1 output
plus(count) # --> (6) The count has never changed even at this point

If you use the global variable count to do what you want...

defplus(lastCount): #What this function does is:
    NowCount = lastCount +1 # If you add a number, it'll be +1
    print(nowCount) # Print that out
    return nowCount #Returns the number you just printed.

count = 0 # Now specify the initial value of a particular variable and
For i in range (3): # When you turn the loop,
    The count = plus(count) # function changes the value to +1 and is repeatedly executed.


2022-09-20 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.