In this blog post, we’ll discuss functions in Python programming.
A function must have a name by which it can be called in other parts of the program. The composition of the function name follows the same rules as the naming of an identifier. A function must have an interface through which information is transferred from the calling program part to the context of the function. An interface can consist of any number of parameters (possibly none). Within the function, each of these parameters is given a name. They can then be used like references in the function body. A function must return a value. Each function automatically returns None if the return value is not explicitly specified.
To define a function in Python, you can use the def keyword. The syntax of the definition looks like this:
def function_name(parameter_1, …, parameter_n):
Statement_1
Statement_2
…
The def keyword is followed by the selected function name. After that, the names of all parameters are listed in parentheses. The definition of the interface is followed by a colon and, indented by one step, the function body. The function body can be any code block in which the parameter names may be used as references. Within the function body, you can also call functions.
Let's consider the actual implementation of a function that calculates the factorial of an integer and prints the result on the screen:
def fac(number):
result = 1
for i in range(2, number+1):
result *= i
print(result)
With this example you can easily understand how the number parameter is processed in the function body. After the calculation is done, the result is output via print. The number reference is defined only inside the function body and has nothing to do with other references outside the function.
When you save and run the preceding example now, you’ll notice that no error message is displayed, but nothing else happens either. Well, that's because we've only defined one function so far. To see it in action, we need to call them at least once. The following program reads numbers from the user in a loop and calculates their factorial using the function just defined:
def fac(number):
result = 1
for i in range(2, number+1):
result *= i
print(result)
while True:
user_input = int(input("Enter a number: "))
fac(user_input)
You can see that the source code has been split into two components: first, the function definition at the top, and second, the main program to be executed at the bottom. The main program consists of an infinite loop in which the fac function is called with the entered number as parameter.
Learn more about Python programming here.
Editor’s note: This post has been adapted from a section of the book Python 3: The Comprehensive Guide by Johannes Ernesti and Peter Kaiser.
Comments