Python 3 functions
Python 3 Functions
A function is a structured, reusable piece of code that performs a single or related function.
Functions increase the modularity of your application and the reusability of your 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 any desired functionality. Here are some simple rules:
- A function block begins with the keyword def, followed by the function identifier name and parentheses ().
- Any arguments and variables must be enclosed in parentheses. Parameters can be defined between parentheses.
- The first line of a function can optionally contain a documentation stringâa placeholder for the function’s description.
- Function bodies begin with a colon and are indented.
- return [expression] Terminates a function, optionally returning a value to the caller. Returning without an expression is equivalent to returning None.
Syntax
Python Functions are defined using the def keyword, in the following general format:
def function name (parameter list):
Function body
By default, parameter values and parameter names are matched in the order they are defined in the function declaration.
Example
Let’s use a function to print “Hello World!”:
>>>def hello() :
print("Hello World!")
>>> hello()
Hello World!
>>>
For a more complex application, use a function with a parameter variable:
Example (Python 3.0+)
#!/usr/bin/python3
# Area calculation function
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("Geekdoc")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h)))
The above example outputs:
Welcome Geekdoc
width = 4 height = 5 area = 20
Function Call
Define a function: give it a name, specify its parameters, and define its code block structure.
Once the basic structure of the function is complete, you can execute it by calling another function or directly from the Python command prompt.
The following example calls the printme() function:
Example (Python 3.0+)
#!/usr/bin/python3
# Define a function
def printme(str):
# Prints any string passed in
print (str)
return
# Call a function
printme("I want to call a user-defined function!")
printme("Call the same function again")
The output of the above example is:
I want to call a user-defined function!
Call the same function again
Parameter Passing
In Python, types belong to objects, and variables do not have types:
a=[1,2,3]
a="Geekdoc"
In the above code, [1,2,3] is of type List, “Geekdoc” is of type String, and the variable a has no type; it is simply a reference (a pointer) to an object, either a List or a String.
Mutable and Immutable Objects
In Python, strings, tuples, and numbers are immutable objects, while lists, dicts, and other objects are mutable.
Immutable type: When a variable is assigned the value a=5 and then a=10, a new int value object 10 is actually created and a is made to point to it. 5 is discarded, but the value of a is not changed; it is equivalent to creating a new a.-
Mutable type: When a variable is assigned the value la=[1,2,3,4] and then la[2]=5, the value of the third element in list la is changed. la itself remains unchanged, only part of its internal value is modified.
Parameter passing in Python functions:
Immutable type: Similar to value passing in C++, such as integers, strings, and tuples. For example, in fun(a), only the value of a is passed; the object itself is not affected. For example, modifying the value of a within fun(a) only modifies a copy of the object and does not affect a itself.-
Mutable types: Similar to passing by reference in C++, such as lists and dictionaries. For example, in fun(la), la is actually passed; modifications to la outside of fun will also affect it.
In Python, everything is an object. Strictly speaking, we can’t talk about passing by value or by reference; we should talk about passing immutable objects and passing mutable objects.
Passing Immutable Object Instances in Python
Example (Python 3.0+)
#!/usr/bin/python3
def ChangeInt( a ):
a = 10
b = 2
ChangeInt(b)
print( b ) # Result is 2
The instance contains the int object 2, and the variable b points to it. When passed to the ChangeInt function, the variable b is copied by value. Both a and b point to the same Int object. When a = 10, a new int value object 10 is generated, and a is made to point to it.
Passing Mutable Object Instances
If a mutable object modifies its parameters within a function, the original parameters will also be changed in the function that calls it. For example:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def changeme( mylist ):
"Modify the passed list"
mylist.append([1,2,3,4])
print ("Value inside the function: ", mylist)
return
# Call the changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Value outside the function: ", mylist)
The object passed into the function and the object appended to the end use the same reference. The output is as follows:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the 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 parameters
- Keyword parameters
- Default parameters
- Variable-length parameters
Required parameters
Required parameters must be passed to the function in the correct order. The number of required parameters must match the number in the declaration.
When calling the printme() function, you must pass an argument, otherwise a syntax error will occur:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printme(str):
"Print any string passed in"
print (str)
return
# Calling the printme function without an argument will result in an error
printme()
Output of the above example:
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; function calls use keyword arguments to determine the values of the arguments passed in.
Using keyword arguments allows the order of arguments in a function call to differ from the order in which they were declared, because the Python interpreter can match argument names to values.
The following example uses parameter names when calling the printme() function:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description available
def printme( str ):
"Prints any string passed in"
print (str)
return
# Calling the printme function
printme( str = "Geek Tutorial")
The above example outputs:
Geek Tutorial
The following example demonstrates that function parameters do not need to be used in a specific order:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description available
def printinfo( name, age ):
"Print any string passed in"
print ("Name: ", name)
print ("Age: ", age)
return
#Call the printinfo function
printinfo(age=50, name="Geekdoc")
The above example outputs:
Name: Geekdoc
Age: 50
Default Parameters
When calling a function, if no parameters are passed, the default parameters are 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 ):
“Prints any string passed in”
print (“Name: “, name)
print (“Age: “, age)
return
# Call the printinfo function
printinfo( age=50, name=”Geekdoc” )
print (“————————“)
printinfo( name=”Geekdoc” )
Output of the above example:
Name: Geekdoc
Age: 50
------------------------
Name: Geekdoc
Age: 35
Variable-Length Arguments
You may need a function to handle more arguments than initially specified. These are called variable-length arguments, and unlike the two types of arguments above, 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 preceded by an asterisk (*) are imported as tuples containing all unnamed variable arguments.
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printinfo( arg1, *vartuple ):
"Print any arguments passed in"
print ("Output: ")
print (arg1)
print (vartuple)
# Call the printinfo function
printinfo( 70, 60, 50 )
The above example outputs:
Output:
70
(60, 50)
If no arguments are specified when calling a function, it is an empty tuple. We can also pass unnamed variables to the function without specifying them. The following example:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def printinfo( arg1, *vartuple ):
"Print any passed parameters"
print ("Output: ")
print (arg1)
for var in vartuple:
print (var)
return
# Call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
The above example outputs:
Output:
10
Output:
70
60
50
Another way is to use a parameter with two asterisks **The basic syntax is as follows:
Output:
10
Output:
70
60
50
Another way is to use a parameter with two asterisks **The basic syntax is as follows:
Output:
1
{'a': 2, 'b': 3}
When declaring a function, the asterisk * can appear alone in the parameters, for example:
def f(a,b,*,c):
return a+b+c
If an asterisk * appears alone, the argument following it must be passed as a keyword.
>>> 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) # Normal
6
>>>
Anonymous Functions
Python uses lambda to create anonymous functions.
Anonymous means that a function is no longer defined using the standard def statement.
- A lambda is just an expression; its function body is much simpler than def.
- The body of a lambda expression is an expression, not a code block. Only limited logic can be encapsulated within a lambda expression.
- A lambda function has its own namespace and cannot access parameters outside its own parameter list or those in the global namespace.
- Although lambda functions appear to be written on a single line, they are not equivalent to inline functions in C or C++. The purpose of inline functions is to increase runtime efficiency by eliminating stack memory usage when calling small functions.
Syntax
The syntax of a lambda function consists of only one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
The following example:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
sum = lambda arg1, arg2: arg1 + arg2
# Calling the sum function
print ("The added value is: ", sum(10, 20))
print ("The added value is: ", sum(20, 20))
The output of the above example:
</pre>
<hr>
<h2>Return Statement</h2>
<p><b>return [expression]</b></b> is used to exit a function, optionally returning an expression to the caller. A return statement without an argument returns None. The previous examples didn't demonstrate how to return a value. The following example demonstrates the use of the return statement:
Example (Python 3.0+)
#!/usr/bin/python3
# Function description
def sum(arg1, arg2):
# Returns the sum of two arguments.
total = arg1 + arg2
print ("Inside function: ", total)
return total
# Call the sum function
total = sum(10, 20)
print ("Outside function: ", total)
<p>The above example outputs:
<pre><code class="language-python line-numbers">Inside function: 30
Outside function: 30
<hr>
<h2>Mandatory positional parameters</h2>
<p>Python 3.8 A new function parameter syntax, /, has been added to indicate that function parameters must be positional and not keyword-based. </p>
<p>In the following example, parameters a and b must be positional, c or d can be either positional or keyword, and e or f must be keyword:</p>
<pre><code class="language-python line-numbers">def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
The following is correct:
f(10, 20, 30, d=40, e=50, f=60)
The following will result in an error:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument