Python Functions Tutorial
In Python, a function is a reusable block of code that performs a specific task. Functions are only executed when they are explicitly called. They can accept inputs, referred to as parameters, and can also return outputs upon execution.
Creating a Function
To define a function in Python, the def
keyword is used, followed by the function name and parentheses:
def my_function():
print("Hello from a function")
Calling a Function
Once defined, you can call a function using its name followed by parentheses:
def my_function():
print("Hello from a function")
my_function()
Function Arguments
Functions can receive information through arguments. These arguments are placed within the parentheses in the function definition.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters vs. Arguments
In Python terminology, a parameter is the variable in the function definition, while an argument is the value passed to the function during the call.
Multiple Arguments
Functions can have multiple arguments, separated by commas:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments (*args)
Use *args
when the number of arguments is unknown. It allows the function to accept a variable number of arguments:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Keyword Arguments
Keyword arguments are passed with the syntax key=value
. Order does not matter:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Arbitrary Keyword Arguments (**kwargs)
Use **kwargs
when the number of keyword arguments is unknown. It creates a dictionary of the passed values:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Values
Functions can have default parameter values, which are used if no argument is provided during the function call:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing Lists as Arguments
You can pass any data type to a function. When passing a list, it remains a list inside the function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To return a value from a function, use the return
statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
If a function body is syntactically required but no action is needed, use the pass
statement:
def myfunction():
pass
Positional-Only Arguments
Add a comma and forward slash , /
after arguments to enforce positional-only usage:
def my_function(x, /):
print(x)
Keyword-Only Arguments
To enforce keyword-only parameters, use an asterisk *
before the keyword-only arguments:
def my_function(*, x):
print(x)
Combining Positional and Keyword Arguments
You can combine both types within a single function:
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
Recursion in Python
Python supports recursion, where a function calls itself. This technique is often used in mathematical computations.
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)
Recursion should be used with caution to avoid stack overflows and infinite loops. It is a powerful tool when applied correctly and efficiently.