Python: Passing variables between functions

后端 未结 6 1269
庸人自扰
庸人自扰 2020-11-27 11:41

I\'ve spent the past few hours reading around in here and elsewhere, as well as experimenting, but I\'m not really understanding what I am sure is a very basic concept: pass

6条回答
  •  天命终不由人
    2020-11-27 12:20

    Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

    def defineAList():
        #list = ['1','2','3'] this creates a new list, named list in the current namespace.
        #same name, different list!
    
        list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
        print "For checking purposes: in defineAList, list is",list
        return list
    

    Alternatively, you can pass it around:

    def main():
        new_list = defineAList()
        useTheList(new_list)
    

提交回复
热议问题