Adding Variables Inside Functions for Python

This question already has an answer here:

  • Using global variables in a function other than the one that created them 18 answers

  • It's because of a thing called scope. You can read up about it, but essentially it means that inside a function, you may not have access to things defined on the outside.

    To make the function aware of these variables, you need to pass them in. Try this:

    a = 2
    b = 3
    
    def add(x, y) :
        x = x + y
        print(str(x))
    
    add(a, b)
    

    It's worth noting that these values are being passed into the function, but are actually not modified themselves. I won't go into the complexities surrounding the way variables are passed to functions, but suffice it to say that after you call add(a, b) here, the values of a and b will still be 2 and 3, respectively.


    I guess you are just learning about how to do this stuff, and you really don't want to go making everything global or you're going to get in a big mess.

    Here, a and b are passed into the function. Inside the function, a and b are local variables and are distinct from the ones you declared outside the function

    a = 2
    b = 3
    
    def add(a, b) :
        a = a + b
        print(str(a))
        return a
    
    a = add(a, b)
    

    The return a is so the function returns that local a so you can do something with it

    链接地址: http://www.djcxy.com/p/23890.html

    上一篇: python如何更改全局变量

    下一篇: 为Python添加变量内部函数