How to use local variable in a function and return it?

前端 未结 3 1198
囚心锁ツ
囚心锁ツ 2020-12-15 12:54

I am trying to create a script that sets a local variable, references it from a function, and can return the manipulated value back to the main scope (or whatever it\'s call

3条回答
  •  长情又很酷
    2020-12-15 13:08

    #!/usr/bin/env python
    chambersinreactor = 0; cardsdiscarded = 0;
    
    def find_chamber_discard():
        chambersinreactor = 0
        cardsdiscarded = 0
        chambersinreactor += 1 
        cardsdiscarded += 1 
        return(chambersinreactor, cardsdiscarded)
    
    #Here the globals remain unchanged by the locals.
    #In python, a scope is similar to a 'namespace'
    find_chamber_discard()
    
    print chambersinreactor #prints as 0
    print cardsdiscarded 
    
    #I've modified the function to return a pair (tuple) of numbers.
    #Above I ignored them. Now I'm going to assign the variables in the 
    #main name space to the result of the function call.
    print("=====with assignment===")
    (chambersinreactor, cardsdiscarded) = find_chamber_discard()
    
    print chambersinreactor #  now prints as 1
    print cardsdiscarded 
    
    # Here is another way that doesn't depend on returning values.
    #Pass a dictionary of all the main variables into your function
    #and directly access them from within the function as needed
    
    print("=======using locals===")
    def find_chamber_discard2(_locals):
        _locals['chambersinreactor'] += 1
        _locals['cardsdiscarded'] += 1
        return
    
    find_chamber_discard2(locals())
    
    print chambersinreactor #incremented the value, which was already 1
    print cardsdiscarded 
    

提交回复
热议问题