Python Functions

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.

You can also search for these topics, python function example, python list functions, python function arguments, function programs in python, how to return the python function, use python within function.

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")
You can also search for these topics, python creating a function dynamically, how to create a python function code, parameter for create a default value in python function, python create a lambda function, Example for create a function using python.

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 :-

Hello from a function

You can also search for these topics, python calling a function within a function, calling a function with self using python, call the python inside a function, python before its definition calling a function, arguments used to calling a function using python, python how call a function, Example for python to calling function.

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 abc
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 3
Addition is 8
Addition is 32

You can also search for these topics, python arguments in function, arguments example for python function, type the arguments for python, arguments list in python function, python function arguments to check, python count function arguments, arguments call function using python, functions executed in python arguments default.

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.



You can also search for these topics, python parameter or arguments by value, checking the Parameters or Arguments? using python, differenciate the parameter or arguments in python, python example for arguments, find the errors of python arguments or parameters?, patameter with option using python, python with type of parameters or arguments, python with or withot spaces using parameters or arguments.

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 :-

abc xyz

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 :-

Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in < module>
my_function("abc")
TypeError: my_function() missing 1 required positional argument: 'lname'

You can also search for these topics, python dynamic number of arguments, python Number of Arguments in error, working of function, python format unknown number of arguments, python check for number of arguments, python how to check number of arguments, Example for python number of arguments.

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 Sweden
I am from India
I am from Norway
I am from Brazil

You can also search for these topics, python dufault parameter value none, Default Parameter Value with type using python, example for python Default Parameter Value, python to find the error Default Parameter Value, working of function parameter default value and key in python, python optional parameter default value, python class parameter default value, python function parameter default value and type.

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 :-

9
16



You can also search for these topics, python return values from list, Return Values of function using python, how to check the return value of python, count the python return values, declaration of return values in python, working of python return values, number of return values available using python.

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 :-

india
japan
singapore

You can also search for these topics, python passing a list as an argument example, check the existing of python Passing a List as an Argument, python how to pass a list as an argument and key, python Passing a List as an Argument range, check the unknown List as an Argument to python passing, type of passing argument as a list using python.

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.

You can aslo search for these topics, python the pass statement purpose, python pass Statement example, python pass the statement value, how to check the python pass statement, conditional statement of pass statement in python, pass statement keyword to explain the python.

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 :-

Total Input Numbers : 2
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

You can also search for these topics, python arbitrary arguments, arbitary args before python, python arbitrary arguments, count the args the python, python arbitrary arguments using args default and args function, get the python arbitrary arguments args, Example for python arbitrary arguments args.

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 :-

The youngest child is C

In Python documents, the phrase Keyword Argument is typically reduced to kwargs.

You can also search for these topics, python keyword arguments example, Keyword Arguments without default in python, define the default value in python Keyword Arguments, use the Keyword Arguments order using python, define the keyword arguments dictionary using python, working of python function keyword argument, Example for keyword arguments in python.

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 :-

His last name is Refsnes

You can also search for these topics, python arbitrary keyword arguments **kwargs below, Arbitrary Keyword Arguments, **kwargs condition using python, python example for Arbitrary Keyword Arguments, **kwargs Arbitrary Keyword Arguments in python, check the error of Arbitrary Keyword Arguments **kwargs with python, python funtion with variable length Arbitrary Keyword Arguments, **kwargs.

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

You can also search for these topics, python recursion limit, python recursion python recursion list, example for python recursion, recurtion alternative using python, how to avoid recursion in python, python binary search resursion, python best practices recursion, recursion code with python, python recursion counter, python ways to increment the recursion.