Search code examples
pythonfunctionglobal-variables

How to change variables in Python functions without using 'global'


I have defined some global parameters in Python (that should also be accesible from other files) and I would like to change them inside the class in which they are defined. I read quite often that one way of doing this is to use 'global' when defining the variables inside the function. However, I also read quite often that 'global' should be avoided basically as it is not good style. Now my question is what other opportunities do I have to change my variables? When just passing them to the function as arguments (this was also one suggestion) their values remain the same.

So here is my code:

from random import random

numberOfBuildings = 10
numberOfVehicles = 10
useMonteCarloMethodForScenarioCreation = True

def monteCarloScenarioGeneration(numberOfBuildings, numberOfVehicles):
    numberOfBuildings_MonteCarlo  = int(  numberOfBuildings *random() *2  + 1)
    numberOfVehicles_MonteCarlo  = int(numberOfVehicles *random() *2  + 1)
    
    if useMonteCarloMethodForScenarioCreation ==True:
        numberOfBuildings = numberOfBuildings_MonteCarlo
        numberOfVehicles = numberOfVehicles_MonteCarlo

    

monteCarloScenarioGeneration(numberOfBuildings, numberOfVehicles)

    
print('numberOfBuildings: ', numberOfBuildings)
print('numberOfVehicles: ', numberOfVehicles)

The value of the global variables numberOfBuildings and numberOfVehicles are not changed when the function monteCarloScenarioGeneration is called. They keep the same values that they have after being initialized (10). How can I change the global variables without using the keyword global? I'd appreciate any comments.


Solution

  • You should just be able to use return to change the variables outside of the function, if I'm reading this right.

    As the last line of the function, put

    return numberOfBuildings, numberOfVehicles

    and then when calling the function

    numberOfBuildings, numberOfVehicles = monteCarloScenarioGeneration(numberOfBuildings, numberOfVehicles)