What are functions?
|
A Simple Function
Use the keyword def to create a function. The code below creates a very simple function called Greet which, when called, displays the greeting "hello there"
To call the function type its name followed by round brackets
Parameter Variables - Passing data to your function
What if you want to personalise your function and greet your user by name? You can pass data to the function by creating a parameter variable inside the round brackets. Here is the function again but this time name has been passed into the function on line 3. On line 4 the parameter variable ( data passed in) is used in the print code. On lines 10 and 11 the function has been called ( used) with different values passed in.
Multiple Parameter Variables
You can pass several pieces of data as parameter variables. Seperate each with a comma.
Returning - Passing Data out of your function
You often want to perform a calculation etc within a function and pass out the result. Use the keyword return to pass data out of a function. In the example below two values are passed into the function AddUp. They are added together and then returned on line 4.
On line 10 the function AddUp is called. The data returned from the AddUp function is then stored in the variable result. Note: You can only return one variable ( or one array). |
Using Return to exit out of a function early.
You can use a return to exit out of a function when you have reached your goal. The following function checks the parameter variable and returns the correct day of the week for the number( assuming that the week starts on a Sunday). Since in the GetDayName function call ( on line 20), the number 2 is passed Monday will be returned.
In the GetDayName function the code will reach line 6 where Monday is returned and the function will end without running the rest of the code. This is more efficient that continuing to check once we have already reached the goal.
In the GetDayName function the code will reach line 6 where Monday is returned and the function will end without running the rest of the code. This is more efficient that continuing to check once we have already reached the goal.