Python: Functions
Thursday 20th July 2017 2:15pm
A function allows frequently used sections of code to be grouped together into a self contained unit making code resuse and maintenance much easier. These functions are then called upon as often as needed from other parts of your program. To define a function we start with the def statement followed by the name we want to call the function. When defining a function we can also supply values called a parameters to be passed to the function. Any code belonging to the function needs to be indented and should be applied in multiples of four spaces ending with a blank line:
def energy(mass): # Function returns the energy (joules) for a given mass (E=MC2) speed = 299792458 # Speed of light (metres per second) return long((mass * speed)**2) def show_results(mass): # Subroutine displays the mass, speed and energy print "" print "Mass (kg): %s" % (mass) print "Speed (mps): 299792458" print "---------------------------------" print "Energy (J): %s" % (energy(mass)) # Displays mass, speed and energy mass = 1.56 show_results(mass)
In the above example the computer works its way down the code and when it reaches the def statements it does nothing but make a note of it. It isn’t until reaching line 15 that it assigns the value 1.56 to the variable called mass. Line 16 then takes the value of mass and calls the show_results function passing the value 1.56. The show_results function in turn calls the energy function which performs the calculation and returns the results; the show_results fuction then presents these results.
Output:
Mass: (kg): 1.56 Speed: (mps): 299792458 ---------------------------------- Energy (J): 218721060297391968