In Python, we define a function using the def reserved word followed by optional parameters in parenthesis. The body of the function is indented (very important!).
This defines the function but does not execute the body of the function.
In the below example, we define a new function called greet() which will print Hello Dolly when called.
def greet():
print("Hello Dolly")
Once we have defined a function, we can call (or invoke) it as many times as we like.
greet()
Calling the function executes the functionâs body, in our case, it prints the text âHello Dollyâ.
Hello Dolly
Function Arguments
Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.
In the above example, we had a fixed output from the function (âHello Dollyâ). We can customize this using arguments. In the following revised code, we update the greeting based on the language specified at the time of calling the function:
def greet(lang):
if lang == 'es':
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'
There are a few important things to notice here:
- The function has one parameterÂ
lang. A parameter is a variable which we use in the function definition that is a âhandleâ that allows the code in the function to access the arguments for a particular function invocation. - We use theÂ
if condition to decide what the function should return depending on the argument supplied. If the argument passed isÂes, then the function will returnÂHola. If the argument isÂfr, then the function will returnÂBonjour and so on. - Notice that the function âreturnsâ a value not âprintâ it, i.e., the value will be supplied back to the calling function and then the calling function can do whatever it wants with it.
Now that the function is defined, we can call it in the way we like:
print(greet('es'),"Dolly")
print(greet('fr'),"Dolly")
print(greet('en'),"Dolly")
These calls will output the following:
Hola Dolly
Bonjour Dolly
Hello Dolly
Multiple Arguments
A function can take multiple arguments. To do so, we define more than one parameter in the function definition. While calling the function, we simply add more arguments. The number and order of arguments and parameters must match. The following custom function calculates the area of a rectangle when its length and breadth are passed to it:
def rectangle_area(l,b):
area = l*b
return area
We can then call the function along with print to output the results.
print(rectangle_area(5,4))
This will print â20â.
While writing programs, you will often think about whether to convert a part of your code into a function or not. There are a few guiding principles to help you decide whether to create a function or not to.
- Donât repeat yourself - make it work once and then reuse it
- If something gets too long or complex, break up logical chunks and put those chunks in functions
Exercises
- Make a functionÂ
reverse_string that, given a string, returns that string in reverse. - Make a function that returns âapplesâ if given a string, âorangesâ if given an integer, and âbananasâ if given anything else.