简体   繁体   中英

Python: variables not cumulative passing through functions

I am writing a function for a text adventure I'm making that acts as a progress bar when the player receives experience (which then levels the player up upon reaching 100). For some reason altering the values of my variables inside the function does not change their values outside the function even though I've returned all three. This becomes apparent when I try calling the function twice, each time adding 85 to the variable a .

Within the function, the objective is to pass the value of a to b , check if b is greater than or equal to 100 , if so add 1 to c and remove 100 from b , then reset a to 0 , print the result, and return the new values.

a = new experience b = current experience c = player level

a = 0
b = 0
c = 1

def func_1(a, b, c):
    b = b + a
    loop1 = 0
    while loop1 < 1:
        if b >= 100:
            print(" ")
            print("Add 1!")
            print(" ")
            c = c + 1
            b = b - 100
        else:
            loop1 = loop1 + 1
        a = a - a
        print("c is " + str(c))
        print("b is " + str(b))
        print("a is " + str(a))
        return a
        return b
        return c

a = a + 85
func_1(a, b, c)
a = a + 85
func_1(a, b, c)
print a, b, c

I'm really new to programming so I apologize for any inefficiencies. Thank you for any help and let me know if something doesn't make sense/is unclear.

Couple of things I see here:

First, out of the three return statements at the end of your code, only the first, return a , is executed. A return statement immediately stops execution of the function; return b and return c are never touched.

Second, you're having some confusion with the scope of the variables. a , b , and c defined outside of the function are global variables, while the a , b , and c passed into the function are local to the scope of the function. Thus, any modifications to the variables in your function won't affect the global variables.

You can do two things. First, have a global declaration at the beginning of the function:

def func_1():
    global a
    global b
    global c
    # Function body

This indicates to the function that a , b , and c are global variables that exist outside the function. Thus, passing in arguments is no longer needed; the function will search for variables outside the function. However, this is bad programming practice. The better option is to have func_1 return the modified values and reassign the global values to these new values, like so:

def func_1(a, b, c):
    # Function body
    return (a, b, c)

Then, to call the function and modify the variables outside the function:

a, b, c = func_1(a, b, c)

A couple suggestions:

You have a lot of incrementing going on, and python has specialized syntax for it: b = b + a can be shortened to b += a , c = c + 1 to c += 1 , b = b - 100 to b -= 100 . Also, simply reset a to 0 with a = 0 instead of subtracting a - a . Also, you don't need print(" ") ; print() will suffice.

Next, your while loop is unnecessary. Your function only needs to check once whether b >= 100 , so there's no need to set up a loop. Increment b and then use a simple if statement to level up if necessary:

def func_1(a, b, c):
    b += a
    if b >= 100:
        print("\nAdd 1!\n")
        c += 1
        b -= 100
    a = 0
    # Rest of the function

Inside func_1() the names a,b,c are local . When you change them nothing happens to the external a,b,c . You return the values correctly in the function, but then when calling the function you need to assign the values to the variables like this: a,b,c=func_1(a,b,c) .

Returning a value doesn't set it unless you explicitly assign it in the calling function:

a, b, c = func_1(a, b, c)

Assigning inside the function doesn't affect the outer ones because they are considered "local scope". To counter that declare them global to affect the outer variables:

def func_1():
    global a
    global b
    global c

Only one of these should be implemented

It is generally preferred not to declare globals. Ideally you should make a class for all of this, but these two options would require the least refactoring of your existing code

Note that a global variable (the variables outside of the function) are completely separate from the local variables (the variables inside the function).

This doesn't work because you can only return once. When you returned a, the function immediately stopped. Also, since you didn't set any variable to the returned value, the global variables outside of the loop were unaffected. What you can do is return the a, b, and c values as a tuple, and then set the a, b and c global variables to that tuple.

return (a, b, c)

a, b, c = func_1(a, b, c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM