How to change a variable after it is already defined?

前端 未结 6 1883
一整个雨季
一整个雨季 2020-11-22 07:03

I\'m trying to add or subtract from a defined variable, but I can\'t figure out how to overwrite the old value with the new one.

a = 15

def test():
    a =          


        
6条回答
  •  迷失自我
    2020-11-22 07:13

    I would do it this way:

    def test(a):
        a = a +10
        return a
    
    print(test(15))
    

    Note that in the version hereby proposed there are some things differing from yours.

    First, what I wrote down would create a function that has, as an input, the value a (in this case set to 15 when we call the function -already defined in the last line-), then assigns to the object a the value a (which was 15) plus 10, then returns a (which has been modified and now is 25) and, finally, prints a out thanks to the last line of code:

    print(test(15))
    

    Note that what you did wasn't actually a pure function, so to speak. Usually we want functions to get an input value (or several) and return an input value (or several). In your case you had an input value that was actually empty and no output value (as you didn't use return). Besides, you tried to write this input a outside the function (which, when you called it by saying test(a) the value a was not loaded an gave you the error -i.e. in the eyes of the computer it was "empty").

    Furthermore, I would encourage you to get used to writing return within the function and then using a print when you call it (just like I wrote in the last coding line: print(test(15))) instead of using it inside the function. It is better to use print only when you call the function and want to see what the function is actually doing.

    At least, this is the way they showed me in basic programming lessons. This can be justified as follows: if you are using the return within the function, the function will give you a value that can be later used in other functions (i.e. the function returns something you can work with). Otherwise, you would only get a number displayed on screen with a print, but the computer could not further work with it.

    P.S. You could do the same doing this:

    def test(a):
        a +=10      
        return a
    
    print(test(15))
    

提交回复
热议问题