Python3 Functions
Functions are organized, reusable blocks of code used to perform a single, related action.
Functions enhance the modularity of the application and the reuse of code. You already know that Python provides many built-in functions, such as print()
. But you can also create your own functions, which are called user-defined functions.
Defining a Function
You can define a function with the functionality you desire. Here are some simple rules:
The function block starts with the def keyword, followed by the function identifier and parentheses ().
Any input parameters and arguments must be placed within the parentheses, and parameters can be defined within the parentheses.
The first statement of the function can optionally be a documentation string—used to store the function's description.
The function content starts with a colon
:
and is indented.return [expression] ends the function, optionally returning a value to the caller. A return statement without an expression is equivalent to returning
None
.
Syntax
Python defines functions using the def keyword, with the following general format:
def function_name(parameter_list):
function_body
By default, parameter values and parameter names are matched according to the order defined in the function declaration.
Example
Let's use a function to output "Hello World!":
#!/usr/bin/python3
def hello():
print("Hello World!")
hello()
A more complex example, with function parameters:
Example (Python 3.0+)
Compare two numbers and return the larger one:
#!/usr/bin/python3
def max(a, b):
if a > b:
return a
else:
return b
a = 4
b = 5
print(max(a, b))
Output of the above example:
5
Example (Python 3.0+)
Calculate the area function:
#!/usr/bin/python3
# Calculate area function
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("tutorialpro")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
Output of the above example:
Welcome tutorialpro
width = 4 height = 5 area = 20
Function Calls
Defining a function gives it a name, specifies the parameters it contains, and outlines its structure.
Once the basic structure of the function is complete, you can execute it by calling it from another function or directly from the Python command prompt.
Here is an example calling the printme() function:
Example (Python 3.0+)
#!/usr/bin/python3
# Define function
def printme(str):
# Print any string passed into the function
print(str)
return
# Call function
printme("I'm calling a user-defined function!")
printme("Calling the same function again")
Output of the above example:
I'm calling a user-defined function!
Calling the same function again
Parameter Passing
In Python, types belong to objects, and objects have different types, but variables do not have types.
a=[1,2,3]
a="tutorialpro"
In the above code, [1,2,3] is a List type, "tutorialpro" is a String type, and the variable a has no type; it is just a reference to an object (a pointer), which can point to a List type object or a String type object.
Mutable and Immutable Objects
In Python, strings, tuples, and numbers are immutable objects, while lists and dictionaries are mutable objects.
Immutable types: When a variable is assigned a=5 and then a=10, a new int value object 10 is created, and a points to it, while 5 is discarded. It does not change the value of a but rather creates a new a.
Mutable types: When a variable is assigned la=[1,2,3,4] and then la[2]=5, it changes the third element of list la. The list la itself is not moved, only some of its internal values are modified.
Python function parameter passing:
- Immutable types: Similar to pass-by-value in C++, such as integers, strings, and tuples. For example, in
fun(a)
, only the value of a is passed, and the a object itself is not affected. If a's value is modified insidefun(a)
, a new a object is created. Mutable Types: Similar to C++'s pass by reference, such as lists and dictionaries. For example, infun(la)
,la
is actually passed, and any modifications inside the function will affect thela
outside the function.
In Python, everything is an object, and strictly speaking, we cannot say it's pass by value or pass by reference; we should say it's passing immutable objects or mutable objects.
Python Passing Immutable Objects Example
Using the id() function to observe memory address changes:
Example (Python 3.0+)
def change(a):
print(id(a)) # Points to the same object
a=10
print(id(a)) # A new object
a=1
print(id(a))
change(a)
The output of the above example is:
4379369136
4379369136
4379369424
It can be seen that before and after the function call, the formal and actual parameters point to the same object (same object id), but after modifying the formal parameter inside the function, it points to a different id.
Passing Mutable Objects Example
Modifications to mutable objects within a function will affect the original parameter in the calling function. For example:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def changeme( mylist ):
"Modify the incoming list"
mylist.append([1,2,3,4])
print ("Value inside function: ", mylist)
return
# Call the changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Value outside function: ", mylist)
The object used for the function call and the new content appended at the end share the same reference. Hence, the output is as follows:
Value inside function: [10, 20, 30, [1, 2, 3, 4]]
Value outside function: [10, 20, 30, [1, 2, 3, 4]]
Parameters
The following are the formal parameter types that can be used when calling a function:
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments
Required arguments must be passed to the function in the correct order. The number of arguments during the call must match the declaration.
Calling the printme()
function requires passing one argument; otherwise, a syntax error will occur:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printme( str ):
"Print any incoming string"
print (str)
return
# Call the printme function without an argument
printme()
The output of the above example is:
Traceback (most recent call last):
File "test.py", line 10, in <module>
printme()
TypeError: printme() missing 1 required positional argument: 'str'
Keyword Arguments
Keyword arguments are closely related to function calls, allowing the function call to determine the values of the arguments.
Keyword arguments allow the order of the arguments in the function call to be inconsistent with the declaration, as the Python interpreter can match parameter names with values.
The following example uses keyword arguments when calling the printme()
function:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printme( str ):
"Print any incoming string"
print (str)
return
# Call the printme function
printme( str = "tutorialpro.org")
The output of the above example is:
tutorialpro.org
The following example demonstrates that the order of function parameters does not need to be specified:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printinfo( name, age ):
"Print any incoming string"
print ("Name: ", name)
print ("Age: ", age)
return
# Call the printinfo function
printinfo( age=50, name="tutorialpro" )
The output of the above example is:
Name: tutorialpro
Age: 50
Default Arguments
If no parameter is passed when calling the function, the default parameter is used. In the following example, if the age
parameter is not passed, the default value is used:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printinfo( name, age = 35 ):
"Print any incoming string"
print ("Name: ", name)
print ("Age: ", age)
return
# Call the printinfo function
printinfo(age=50, name="tutorialpro")
print("------------------------")
printinfo(name="tutorialpro")
The above example outputs:
Name: tutorialpro
Age: 50
------------------------
Name: tutorialpro
Age: 35
Variable-length Arguments
You may need a function that can handle more arguments than it was initially declared to accept. These arguments are called variable-length arguments and are different from the two types mentioned above, as they are not named when declared. The basic syntax is as follows:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Arguments prefixed with an asterisk *
are imported as a tuple, containing all unnamed variable arguments.
Example (Python 3.0+)
#!/usr/bin/python3
# Function definition is here
def printinfo(arg1, *vartuple):
"Prints any number of input arguments"
print("Output: ")
print(arg1)
print(vartuple)
# Now you can call printinfo function
printinfo(70, 60, 50)
The above example outputs:
Output:
70
(60, 50)
Example (Python 3.0+)
#!/usr/bin/python3
# Function definition is here
def printinfo(arg1, *vartuple):
"Prints any number of input arguments"
print("Output: ")
print(arg1)
for var in vartuple:
print(var)
return
# Now you can call printinfo function
printinfo(10)
printinfo(70, 60, 50)
The above example outputs:
Output:
10
Output:
70
60
50
Another type of argument is prefixed with two asterisks **
. The basic syntax is as follows:
def functionname([formal_args,] **var_args_dict ):
"function_docstring"
function_suite
return [expression]
Arguments prefixed with two asterisks **
are imported as a dictionary.
Example (Python 3.0+)
#!/usr/bin/python3
# Function definition is here
def printinfo(arg1, **vardict):
"Prints any number of input arguments"
print("Output: ")
print(arg1)
print(vardict)
# Now you can call printinfo function
printinfo(1, a=2, b=3)
The above example outputs:
Output:
1
{'a': 2, 'b': 3}
When declaring a function, an asterisk *
can appear alone. For example:
def f(a, b, *, c):
return a + b + c
If an asterisk *
appears alone, arguments after the *
must be passed as keywords:
>>> def f(a, b, *, c):
... return a + b + c
...
>>> f(1, 2, 3) # Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1, 2, c=3) # Correct
6
>>>
Anonymous Functions
Python uses lambda
to create anonymous functions.
An anonymous function means that a function is defined without using the def
standard statement.
lambda
is just an expression, and the function body is simpler than that ofdef
.The body of a lambda is an expression, not a block of code. It can only encapsulate limited logic.
A lambda function has its own namespace and cannot access parameters outside its parameter list or the global namespace.
Although a lambda function appears to be written in one line, it is not the same as an inline function in C or C++, which aims to save stack memory when calling small functions.
Syntax
The syntax of a lambda function contains only one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
To add 10 to the parameter a:
Example
x = lambda a: a + 10
print(x(5))
Output:
15
The following example sets up an anonymous function with two parameters:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
sum = lambda arg1, arg2: arg1 + arg2
# Calling the sum function
print("The sum is : ", sum(10, 20))
print("The sum is : ", sum(20, 20))
Output:
The sum is : 30
The sum is : 40
We can encapsulate the anonymous function within a function, allowing us to create multiple anonymous functions using the same code.
The following example encapsulates the anonymous function within the myfunc
function, creating different anonymous functions by passing different parameters:
Example
def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:
22
33
return Statement
The return [expression] statement is used to exit a function, optionally passing back an expression to the caller. A return statement with no arguments returns None. Previous examples did not demonstrate how to return values, the following example shows the usage of the return statement:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def sum(arg1, arg2):
# Return the sum of two arguments.
total = arg1 + arg2
print("Inside the function : ", total)
return total
# Calling the sum function
total = sum(10, 20)
print("Outside the function : ", total)
Output:
Inside the function : 30
Outside the function : 30
Positional-Only Parameters
Python 3.8 introduced a new function parameter syntax /
to indicate that certain function parameters must be specified positionally and cannot be used as keyword arguments.
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
The following usage is correct:
f(10, 20, 30, d=40, e=50, f=60)
The following usage will result in an error:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be used as a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be used as a keyword argument
x = True
def printLine(text):
print(text, ' tutorialpro')
printLine('Python')
def greetPerson(*name):
print('Hello', name)
greetPerson('tutorialpro', 'Google')
result = lambda x: x * x
print(result(5))
def Foo(x):
if (x==1):
return 1
else:
return x+Foo(x-1)
print(Foo(4))
numbers = [1, 3, 6]
newNumbers = tuple(map(lambda x: x , numbers))
print(newNumbers)