Cannot call a variable from another function

后端 未结 4 759
陌清茗
陌清茗 2021-01-24 08:07

I edited my thread based on feedback. Basically, I need to use a couple of variables from function 1, and I need to print it in function 2.

How do I go about doing that?

4条回答
  •  死守一世寂寞
    2021-01-24 08:26

    Option 1: use global variables. - Using global variables in a function other than the one that created them (for examples)

    Option 2: return the values

    ex.

    def func_one():
        var1 = 1
        var2 = 2
        return var1, var2
    
    def func_two(a,b):
        print a
        print b    
    
    # you can return to multiple vars like:
    one, two = func_one()
    func_two(one, two)
    
    # this would print 1 and 2
    
    # if you return multiple values to one var, they will return as a list
    # returning one value per function may keep your code cleaner
    the_vars = func_one()
    func_two(the_vars[0], the_vars[1])
    
    # this would print 1 and 2 also
    

提交回复
热议问题