Functions in Python for Beginners
In this section, we will learn about functions—sets of instructions that can take input, perform tasks, and get output. Functions let you define and reuse specific functionality in a compact form.
Calling a function means passing it the input needed for execution and getting a result. When you pass input to a function, it’s called passing a parameter.
Functions in Python are similar to mathematical functions in algebra. For example, in algebra, a function is defined like this:
f(x) = x * 2
The left side defines the function f, which takes one parameter, x. The right side is the function definition, which uses x to perform a calculation and get a result. Here, the function’s value is its parameter multiplied by two.
In Python, a function is written as follows: function_name(parameters_separated_by_commas). To call a function, specify parentheses after its name and place the parameters inside, separating each with a comma. To create functions in Python, choose a name, define the parameters, specify what the function should do, and what value it should get.
def function_name(parameters):
function_definition
The mathematical function f(x) = x * 2 in Python would look like this:
def f(x):
return x * 2
The keyword def tells Python you are defining a function. After def, specify the function’s name; it must follow the same rules as variable names. By convention, function names should not use capital letters, and words should be separated by underscores like_this.
Once you’ve named your function, specify parentheses after it. Inside the parentheses, there should be one or more parameters.
After the parentheses, place a colon, and start a new line with an indentation of four spaces. Any code indented by four spaces after the colon is the function body. In this case, the body of our function consists of only one line:
return x * 2
The keyword return is used to define the value that the function gets when called.
To call a function in Python, use the syntax function_name(parameters, separated, by, commas).
Below is a call to the function f from the previous example with the parameter 2.
f(2)
The console did not output anything. You can save the output of your function in a variable and pass it to the print function.
# Continuation
# of the previous example
def f(x):
return x * 2
result = f(2)
print(result) # 4
You can save the result returned by your function in a variable and use this value in the program later.
def f(x):
return x + 1
z = f(4)
if z == 5:
print("z equals 5")
else:
print("z does not equal 5")
A function can have one parameter, multiple parameters, or none at all. To define a function that requires no parameters, leave the parentheses empty.
def f():
return 1 + 1
result = f()
print(result) # 2
If you want a function to accept more than one parameter, separate each parameter in the parentheses with a comma.
def f(x, y, z):
return x + y + z
result = f(1, 2, 3)
print(result) # 6
Finally, a function does not have to contain a return statement. If there is nothing for the function to return, it gets the value None.
def f():
z = 1 + 1
result = f()
print(result) # None
Required and Optional Parameters
A function can accept two types of parameters. Those you’ve encountered so far are called required parameters. When a user calls a function, they must pass all required parameters, otherwise Python will generate an exception.
Python also has another type of parameter—optional parameters. Optional parameters are defined using the following syntax: function_name(parameter_name=parameter_value). Like required parameters, optional parameters should be separated by commas. Below is an example of a function that uses an optional parameter.
def f(x=2):
return x**x
print(f()) # 4
print(f(4)) # 16
First, the function is called without passing a parameter. Since the parameter is optional, x automatically becomes 2, and the function gets 4.
Then the same function is called with the parameter 4. Thus x will be 4 and the function will get 16. You can define a function that accepts both required and optional parameters, but required ones must be defined first.
def add(x, y=10):
return x + y
result = add(2)
print(result)