Python Functions


A function is a code block that only works when called.

You can transfer data, also known as parameters, to a function.

The function can restore data as a result.


Creating a Function

In Python the function is defined using def keyword:


Example
def my_function():
  print("Hello from a function")


Calling a Function

To call a function, use the job name followed by parentheses:


Example
def my_function():
  print("Hello from a function")

my_function()


Arguments

Information can be passed on to activities as arguments.

Arguments are clarified after the name of the function, within brackets. You can add as many arguments as you like, just separate them with commas.

The following example contains a function with one argument (fname). When a function is called, we convey the first word, which is used within the function to print the full name:


Example
def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to form args in Python texts.



Parameters or Arguments?

The words parameter and argument can be applied to the same thing: information transmitted to a function.


From a function's perspective:

The parameter is a variable in the brackets list in the job description.

An argument is the amount sent to an employee when it is called.



Number of Arguments

By default, the function should be called the correct number of arguments. Which means if your job is expecting 2 arguments, you should call the job 2 arguments, not more, and not less.


Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to drive a job with 1 or 3 issues, you will get an error:


Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil")


Arbitrary Arguments, *args

If you do not know how many arguments will be referred to your work, add * before the parameter name in the job description.

This way the job will get a lot of arguments, and you can get things right:


Example

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Negative Arguments are often abbreviated as * args in Python texts.



Keyword Arguments

You can also submit arguments with key = value syntax.

In this way the order of the disputes does not matter.


Example
def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The term Keyword Arguments is often abbreviated to query in Python texts.


Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments will be transferred to your task, add two stars: ** before the parameter name in the job description.

In this way the employee will receive a dictionary of arguments, and you can access the material accordingly:


Example

If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

The Arbitrary Kword Arguments are often abbreviated as ** kwargs in Python texts.



Default Parameter Value

The following example illustrates how to use a default parameter value.

When we call a function without conflict, we use the default value:


Example
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")


Passing a List as an Argument

You can send any type of conflict data to the task (character unit, number, list, dictionary etc.), and it will be treated as the same data type within the function.

Eg. if you submit a List as an argument, it will still be a List when it reaches the function:


Example
def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)


Return Values

To allow the function to restore value, use the return statement:


Example
def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))


The pass Statement

function definitions can not be empty, but if for some reason you have a function definitions that does not contain content, submit a pass statement to avoid finding error.


Example
def myfunction():
  pass


Recursion

Python also accepts duplication of function, which means that the specified function can call itself.

Recursion is a common mathematical concept and system. It means the work is costly. This has the benefit of meaning that you can connect to the data to achieve the result.

The developer should be careful about repetition as it may be easier to write a non-stop work, or one that uses excessive memory or processing power. However, a well-written repetition can be a very efficient and mathematical method in systems.

In this example, tri_recursion() is a function we have defined as "recurse". We use the k variable as data, decreasing (-1) each time we repeat. Recursion ends when the condition is greater than 0 (i.e. if it is 0).

For a new engineer it can take a while to figure out how this really works, the best way to find out is to test it and fix it.


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)