So I have worked my way through the Python ‘Physics Class’ project on the Comp. Science track.
In the project you create some functions and then use said functions later in another function. The functions I am posting in relation to are the get_force() & get_work() functions. My question is around the use of global variables. In my get_work() function I called a variable that only existed in the get_force() function:
global n_force # Made n_force global as it is used in get_work() function
train_mass = int(input("What is the train’s mass in kg? ")) # Inputs make more flexible
train_acceleration = int(input("What is the train’s acceleration? "))
n_force = train_mass*train_acceleration
print(“The GE train supplies " + str(n_force) + " Newtons of force.”)
get_force() # Calls the get_force() function to eliminate repetition
n_distance = int(input("What is the distance of travel? "))
n_work = n_force * n_distance # Calls the global variable - n_force
print(“The GE train does " + str(n_work) + " Joules of work over " + str(n_distance) + " metres.”)
Is it best to avoid using global variables in the above way? If so, can I ask why? Is there some security issue with it or possibly breaks code when you work on more complex tasks?