Python functionslast modified July 6, 2020In this part of the Python programming tutorial, we cover functions in Python.Python function definitionA function is a block of reusable code that is used to perform a specific action. The advantages of using functions are:Reducing duplication of codeDecomposing complex problems into simpler piecesImproving clarity of the codeReuse of codeInformation hidingFunctions in Python are first-class citizens. It means that functionshave equal status with other objects in Python. Functions can be assigned to variables, stored in collections, or passed as arguments. This brings additional flexibility to the language.Python function typesThere are two basic types of functions: built-in functions and user defined functions. The built-in functions are part of the Python language; for instance dir(), len(), or abs(). The user defined functions are functions created with the defkeyword.Python creating functionsA function is created with the defkeyword. The statements in the block of the function must be indented.def function():pass
The defkeyword is followed by the function name with round brackets and a colon. The indented statements form a bodyof the function.The function is later executed when needed. We say that we callthe function. If we call a function, the statements inside the function body are executed. They are not executed until the function is called.myfunc()To call a function, we specify the function name with the round brackets.ret.py#!/usr/bin/env python"""The ret.py script shows how to work withfunctions in Python.Author: Jan BodnarZetCode, 2019"""def show_module_name():print(__doc__)def get_module_file():return __file__a = show_module_name()b = get_module_file()print(a, b)The string at the top of the script is called the documentation string. It documents the current script. The file in which we put Python code is called a module.We define two functions. The first function prints the module documentation string. The second returns the path of the module. Function may or may not return a value. If a funciton does not return a value, it implicitly returns None.
The __doc__and __file__are special state attributes. Note that there are two underscores on both sides of the attribute.$ ./ret.pyThe ret.py script shows how to work withfunctions in Python.Author: Jan BodnarZetCode, 2019None C:/Users/Jano/PycharmProjects/Simple/simple.pyThis is the output of the program.Definitions of functions must precede their usage. Otherwise the interpreter will complain with a NameError.func_prec.py#!/usr/bin/env python# func_prec.pydef f1():print("f1()")f1()#f2()def f2():print("f2()")In the above example, we have two definitions of functions. One line is commented. A function call cannot be ahead of its definition.