A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
1. Define function (def) and Call function
In Python a function is defined using the def keyword.
To call a function, use the function name followed by parenthesis.
def my_function():
print("Hello from a function")
# Calling the function
my_function()
2. Arguments (positional, keyword)
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
Keyword Arguments (kwargs)
You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
3. Default arguments
If we call the function without argument, it uses the default value.
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden") # Prints Sweden
my_function() # Prints Norway (default)
4. Variable-length arguments (*args, **kwargs)
If you do not know how many arguments that will be passed into your function, you can use variable-length arguments.
Arbitrary Arguments, *args
Add a * before the parameter name. The function will receive a tuple of arguments.
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Arbitrary Keyword Arguments, **kwargs
Add two asterisks ** before the parameter name. The function will receive a dictionary of arguments.
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
5. Return values
To let a function return a value, use the return statement.
def my_function(x):
return 5 * x
print(my_function(3)) # 15
print(my_function(5)) # 25
6. Pass statement in functions
Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
7. Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
tri_recursion(6)
Discussion
Loading comments...