Python Functions
A function is a code block that only executes when it is invoked.
Data known as parameters can be passed into a feature.
This allows a function to return data.
Creating a Function
The def
keyword is used to create or declare a user defined function in python.
Example :- Creating a simple fuction called "my_function" :
def my_function():
print("Hello from a function")
Calling a Function
To call or invoke a function use the parenthesis () following with function name.
Example :- Calling the my_function which is created above :
my_function()
Output :-
Function Arguments
Information can be transferred as arguments into functions.
After a function name, arguments within the parentheses are supplied. You can just separate as many arguments as you like by a comma.
Example 1 :- The example below has one argument function (name). When the function is invoked, a name will be passed to print the name within the function :
def sayHi(name):
print("Hi " + name)
sayHi("abc")
sayHi("xyz")
Output :-
Hi xyz
Example 2 :- The below function has two argument (no1, no2) :
def doAdd(no1, no2):
result = "Addition is {}"
print(result.format(no3))
doAdd(1, 2)
doAdd(3, 5)
doAdd(10, 22)
Output :-
Addition is 8
Addition is 32
Parameters or Arguments?
The parameter and argument can be used for the same purpose : information which is transferred to a function.
From the perspective of a function :
A parameter is the variable in the function definition that appears within the parentheses.
An argument is the value that is sent when it is called to the function.
Related Links
Number of Arguments
A function with the correct amount of parameters must be invoked by default. This means you must call the function with 2 arguments, not more, not fewer if your function expects 2 arguments.
Example 1 :- This function expects 2 arguments and gets 2 arguments :
def my_function(fname, lname):
print(fname + " " + lname)
my_function("abc", "xyz")
Output :-
If one or three arguments attempt to call the function, an error will be found :
Example 2 :- This method has two arguments, but supplied only 1 :
def my_function(fname, lname):
print(fname + " " + lname)
my_function("abc")
Output :-
File "demo_function_args_error.py", line 4, in < module>
my_function("abc")
TypeError: my_function() missing 1 required positional argument: 'lname'
Default Parameter Value
The example below explains how to utilise a default value.
Example :- If the function is called without argument, the default value is used :
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() # Calling function without argument
my_function("Brazil")
Output :-
I am from India
I am from Norway
I am from Brazil
Return Values
A function can return a value to caller. The return value may be any datatype.
Use the return
keyword declaration to allow a function to return a value.
Example :- A function with return value
def multiply(x):
return x * x
print(multiply(3))
x = multiply(4);
print(x)
Output :-
16
Related Links
Passing a List as an Argument
The parameter can be sent to a function with any data type (string, number and list, dictionary, and so on) and is treated within the function as the same data type.
Example :- For example, when the function reaches the list, if you send an argument, it will still be a line :
def my_function(names):
for x in names:
print(x)
countries = ["india", "japan", "singapore"]
my_function(countries)
Output :-
japan
singapore
The pass Statement
A function definitions may not be empty, however if you have no content for whatever reason, pass
in the statement to avoid an error. If the function
definition is not content.
Example :- Creating a empty function :
def myfunction():
pass
# having an empty function definition like this, would raise an error without the pass statement
Note :- Having an empty function definition like this, would raise an error without the pass statement.
Arbitrary Arguments, *args
If you don't know how many arguments your function is going to get, add a *
in the definition of a function before a parameter name.
The function will thus get a tuple of arguments and can therefore access the items :
Example :- If unknown is the number of arguments, add *
before the name of the parameter :
def addNos(*nos):
count = len(nos)
msg1 = "Total Input Numbers : {}"
print(msg1.format(count))
print("The given inputs are")
print(nos)
sum = 0
for x in range(count):
sum = sum + nos[x]
msg2 = "The sum is : {}"
print(msg2.format(sum))
addNos(5, 3)
print()
addNos(2, 1, 7)
Output :-
The given inputs are
(5, 3)
The sum is : 8
Total Input Numbers : 3
The given inputs are
(2, 1, 7)
The sum is : 10
Keyword Arguments
The key = value syntax can additionally send argument.
This doesn't matter in the sequence of the arguments.
Example :-
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "A", child2 = "B", child3 = "C")
Output :-
In Python documents, the phrase
Keyword Argument is typically reduced to kwargs.
Arbitrary Keyword Arguments, **kwargs
To indicate that you don't know how many
keyword arguments will be supplied into your method, add two **
after the parameter name in the code specification.
This enables the function to receive a dictionary of parameters and hence to access the items :
Example :- When keyword numbers are uncertain, add double **
before the name of the parameter :
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Output :-
Recursion
Python also allows the recursion function that can call itself a defined function.
Recursion is a frequent idea for mathematics and programming. That means it calls itself a function. This has the advantage that you can loop data to achieve an outcome.
Recursion should be very careful, as a function that never ends, or that requires excess memory or CPU power is fairly easyl to slip in. But a very effective and mathematical-elegant programming strategy can be written appropriately through recursion.
This example is a function that we have written to call tri_recursion()
("recurse"). The k
variable is used for information which decreases (-1
) every time we resort. The recursion finishes if it does not exceed 0. (i.e. when it is 0)
It may take a while to learn how exactly this works for a new developer, the best approach to find it out is by testing and altering.
Example :- Recursion Example :
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Output :-
Recursion Example Results
1
3
6
10
15
21