Function in python is a block of code designed to perform a specific task. In this tutorial, we will learn about functions in Python with different examples and understand how function can be used to define a module and can be imported into another module. We will also look into how function can be executed as Python scripts.
Functions in python are defined with def keyword followed by function name and arguments starting wih parantheses and a colon(:) to start a new block. We use an optional keyword return to return values from a function. We can also use an empty return keyword for an early return of the function execution. In this case, None is return by the function. Use of function adds modularity in our code and removes duplicacy of the code and makes code reusable.
Syntaxdef function_name(parameters): statement(s)Example
def echo_name(name): print("My name is " + name) echo_name("John")
Expected 2 blank lines after method def.
OutputMy name is John
Default Parameter in Python Function
In python, we can make function parameter optional by providing a default value to the method parameter. Below is an example. The output will be the same as above.
def echo_name(name="John"): print("My name is " + name) echo_name()
If a function accepts 2 arguments, the default parameter must be the last argument of the function. Else you can expect an error as SyntaxError: non-default argument follows default argument. Below is the correct way.
def add(a, b=3): return a + b add(2, 3)
Variable Arguments Function
Python allows to pass variable number of arguments in a function. By convention, we use *args as a arguments in function definitions to accept variable number of arguments. Below is an example
def details(name, *args): for arg in args: print(arg) print("My name is '{}'. I am a '{}'. I stay in '{}'".format(name, args[0], args[1])) details("John", "human", "Canada")
Variable arguments(*args) must be the last argument.
Python also provides ways to accept multiple key value pairs as function argument. By convention, we use *kwargs as a arguments in function definitions to accept such pairs.
def details(**kwargs): for key, value in kwargs.items(): print(key, value) details(Name="John", age=32, gender="Unknown")
Function Return Values
As mentioned above, function performs some specific task and can return computed values after the task done. Below is an example that takes 2 numbers as an input, performs the sum and return the result.
def add(a, b): return a + b print(add(4, 6))
Always remember, the default parameter is always evaluated once. If the default argument is other then litral, than the expected result may vary for default arguments.
def add(fruits=[]): fruits.append("orange") return fruits print(add()) print(add())Output
['orange'] ['orange', 'orange']
In the below example, even if we pause the execution for 10 seconds, the print function prints the same time again
import time def show_time(time=time.ctime()): print(time) show_time() time.sleep(10) show_time()Output
Sat Mar 16 22:09:25 2019 Sat Mar 16 22:09:25 2019
Recursion in Python
Calling the same method by itself contineously untill a particlar condition is satisfied os called recursion. It is not encouraged to use Recursion as it may cause an infinite loop if we miss to implement the exit logic carefully and hence may lead to out of memory. Below example uses recursion to print numbers greater than 0 and less than the input number.
def recursion_example(k): k -= 1 if k > 0: print(k) recursion_example(k) recursion_example(5)
Function Modularity
Modularity enables self contained, reusable code that can be used again and again with import statements without any circular dependency. Let us create a module to print the list of months.
monthlist.pyimport datetime months_choices = [] for i in range(1, 13): months_choices.append((i, datetime.date(2019, i, 1).strftime('%B'))) for month in months_choices: print(month)
To reuse this module in another module, you can import this module as below
test.pyimport monthlist
As soon as you execute test.py, month list will be printed. But this is not an intended behaviour. We want this module to be executed when we actually want. To do so we can wrap it inside a function and from test module we can invoke this function.
test.pyimport datetime def fetch_months(): months_choices = [] for i in range(1, 13): months_choices.append((i, datetime.date(2019, i, 1).strftime('%B'))) for month in months_choices: print(month)test.py
import monthlist monthlist.fetch_months()
We can also import a particular method from a module.
test.pyfrom monthlist import fetch_months fetch_months()
Function Execution as Python Script
Special attributes in Python are delimited by double underscores. One of those idioms is __name__. It evaluates to "__main__" or the actual module name depending on how the enclosing module is being used. With this, we can define our module to either import into another module or execute as a script.
monthlist.py
...
...
print(print(__name__))
If you execute test.py, above print statement o/p will be the name of the module as monthlist
. Now, if you run it as a script from shell, above print statement will output to __main__
.
PS D:\workspace\python\examples> python monthlist.py __main__ PS D:\workspace\python\examples>
Now to execute this function as a script, we can make below changes in monthlist.py
...
...
if __name__ == '__main__':
fetch_months()
Conclusion
In this tutorial, we learnt about functions in Python with different examples and understood how function can be used to define a module and can be imported into another module. We also looked into how function can be executed as Python scripts.