What are functions in Python ?

What are functions in Python ?

Functions are one of the core concepts of the Python programming language. We use them in everyday Python programming.

A function is a code block that you can use in your program as many times as you want. You can do that by "calling" it. While learning how to code, you used the print() function to run your code. You used the input() function to make input. Those functions are called built-in functions. There are two types of functions; built-in functions and user-defined functions. A user-defined function is one that you build and use in your program.

In this tutorial, you will learn about user-defined functions and making function calls, arguments and parameters, and how to import functions into your code.

What are functions in python for beginners

Defining a function

First, to use a function, you will have to define it. You define a function in Python with the def keyword.

This is the syntax to define a function:

def function_name():

For example, if you want to print a simple sentence, you could use a function.

def learning():
  '''Creating a simple function'''

  print('I am learning Python')

In the function above, the triple quotes surrounding the comments are used to explain the purpose of writing the function.

Note: You should always use comments in your functions as a best practice.

The function above is incomplete because you have yet to call it.

Calling A Function

To call a function, you use the name of that function and add brackets to it.

This is the syntax: function_name()

You can also call the function twice or as many times as you like using the same syntax. To call the function in the previous example,

def learning():
  '''Creating a simple function'''

  print('I am learning Python')


learning()
learning()

This will print I am learning Python twice in the terminal.

Arguments and Parameters

The learning function you had written above had an empty bracket. It was a simple function with no parameters.

A parameter is like a variable (a placeholder in memory) passed to a function.

This is the syntax:

def function_name(parameter):

To give the previous example a parameter,

def learning(language):
    '''Creating a simple function'''
    print(f'I am learning {language}')

Now, the function has a parameter language. With this language parameter, you can specify what you are learning. To do that, you need an argument. An argument is a value you use when you want to call a function.

This is the syntax:

function_name(argument)

To use an argument,

def learning(language):
    '''Creating a language function'''
    print(f'I am learning {language}')


learning('python')

Now, you specify by adding the parameter to the print command using f-strings formatting. (Because it is a variable) When you run the code in the terminal, you should get I am learning python.

So, a parameter is for defining a function variable, while an argument is for calling a function value.

You can call the function many times with different values. In each argument, you specify the language you are learning.

I will add one more language to the previous example.

def learning(language):
    '''Creating a language function'''
    print(f'I am learning {language}')


learning('python')
learning('javascript')

When you run it, you should see both values printed on the terminal.

I am learning python
I am learning javascript

One of the awesome things about functions is that it can take multiple parameters .

This is the syntax:

def function_name(parameter1,parameter2,parameter3):

So these multiple parameters also require multiple arguments.

This is the syntax:

function_name(argument1,argument2,argument3)

Types Of Arguments

There are two types of arguments which are: positional arguments and keyword arguments.

1. Positional Arguments

With positional arguments, the parameter names are orderly. Order is important in positional arguments; For example, you could add your name to the previous example. To do that,

def learning(name,language):
    '''A function that describes my name and the language I am learning'''
    print(f'My name is {name} and I am learning {language}')


learning('Ezinne','Python')

In this example, you are using many parameters and many arguments, and you specified them with a comma (,).

In positional arguments, if you changed the order of the arguments like this:

learning('Python','Ezinne')

When you run the code, it would give My name is Python and I am learning Ezinne

This is because you did not place it in order while using positional arguments.

2. Keyword Arguments

In keyword arguments, you specify the values that you add such that there is no need for orderliness. If you were to use keyword arguments in the previous examples, they would be:

learning(language='Python',name='Ezinne')

This would give My name is Ezinne and I am learning Python irrespective of the positioning.

You can specify a single parameter in your function and fill in the other one as an argument.

For example, you could create a function that contains your name and all of the languages you are learning.

def learning(language, name='Ezinne'):
    '''A function that describes my name and the language I am learning'''
    print(f'My name is {name} and I am learning {language}')


learning('python')
learning('javascript')

This would give

My name is Ezinne and I am learning python
My name is Ezinne and I am learning javascript

You don't need to add value to the argument, as the Python interpreter will use the default value (name='Ezinne').

Note: When using default values, you add them only after you have added other non-default arguments.

But if you called the same function and gave it a value of your own, then the Python interpreter would override the default value.

E.g:

def learning(language, name='Ezinne'):
    '''A function that describes my name and the language I am learning'''
    print(f'My name is {name} and I am learning {language}')


learning('python')
learning(name='Anne',language='javascript')

This would give

My name is Ezinne and I am learning python
My name is Anne and I am learning javascript

You specified a value in the argument for the name parameter. The python interpreter ignored the default value and used the name you specified in the argument for the second call, which is learning('Anne','javascript').

You can also use different arguments from the arguments in the parameters.

def learning(name='Ezinne',language='Python'):
    '''A function that describes my name and the language I am learning'''
    print(f'My name is {name} and I am learning {language}')


learning()
learning(language='Golang', name='Emilia')
learning(name='Anne', language='Javascript')

This would give

My name is Ezinne and I am learning Python
My name is Emilia and I am learning Golang
My name is Anne and I am learning Javascript

Using the return keyword

A return keyword will pass the output of your code to the caller of the function. The return keyword ends your program wherever you place it in your function.

This is the syntax:

def function_name(parameter):
    return parameter

In the previous examples you used, you simply printed the values. You can use a return value to return the values instead.

Eg:

def learning(name,language):
    '''A function that describes my name and the language I am learning'''
    return f'My name is {name} and I am learning {language}'


print(learning('Ezinne','python'))
print(learning('Ezinne','javascript'))

This would give

My name is Ezinne and I am learning python
My name is Ezinne and I am learning javascript

When using return in a function, you add the print function when calling the function so it will print on the terminal.

You could also assign the statement you wish to return inside a new variable before you return it.

def learning(name,language):
    '''A function that describes my name and the language I am learning'''
    output = f'My name is {name} and I am learning {language}'
    return output


print(learning('Ezinne','python'))
print(learning('Ezinne','javascript'))

This would give

My name is Ezinne and I am learning python
My name is Ezinne and I am learning javascript

Using dictionaries and lists

You could also use a function to return dictionaries and lists.

1. Dictionaries

In dictionaries, the keys and values are passed inside the function before returning them.

This is the syntax:

def function_name(param1, param2):
   return {'param1': param1, 'param2' : param2}

Eg: You could create a dictionary that returns names and languages.

def learning(name, language):
    '''Creating a dictionary of names and languages'''
    details = {'name' : name, 'language' : language}
    return f'My name is {name} and I am learning {language}'


print(learning('Anne','Python'))
print(learning('Ezinne','Scala'))

Output

My name is Anne and I am learning Python
My name is Ezinne and I am learning Scala

2. Lists

To use a list, you pass the values in the function.

This is the syntax:

def function_name(param1, param2):
   return [param1, param2]

When you are coding, you could want to pass in ten, twenty, or even more values in your function. To do that, you will use a for loop to loop through the list.

See this example:

def todo_list(list):
    '''creating a simple todo list'''
    for thing in list:
        print(f'- {thing}')


things = ['washing','cooking','reading','writing','coding','sleeping','eating','skating']
todo_list(things)

This will give:

- washing
- cooking
- reading
- writing
- coding
- sleeping
- eating
- skating

Args and Kwargs

1. Args

Args lets you pass in an unlimited number of arguments. It uses an asterisk to indicate this.

This is the syntax:

def function_name(*args):

The word Args is a conventional name for it, but you could use any other name you want.

In the previous example, you used a list and a for loop to loop through many arguments.

In this example, you will use args and a for loop to print the list:

def todo_lists(*lists):
    '''creating a simple todo list'''
    for list in lists:
        print(f'- {list}')




todo_lists('washing','cooking','reading','writing','coding','sleeping','eating','skating')

This would give:

- washing
- cooking
- reading
- writing
- coding
- sleeping
- eating
- skating

2. Kwargs

kwargs behaves like a dictionary and it uses the keyword argument method. In the case of kwargs, you do not have to specify all the values you intend to use in the function. You could use a generic name like kwargs or any other name.

This is the syntax:

def function_name(**kwargs):

Like args, kwargs is also a conventional name, you can use any other name you want.

def learning(**details):
    '''Creating a dictionary of names and languages'''
    for name,language in details.items():
        print(f'My name is {name} and I am learning {language}')


learning(Anne='Python',Ezinne='Scala',Emilia='Golang')

This would give:

My name is Anne and I am learning Python
My name is Ezinne and I am learning Scala
My name is Emilia and I am learning Golang

Importing a module

When writing a function, you can import a program you had written in a previous file into the present program.

For example, to import an entire module, you do that with:

Syntax:

import file_name

Command:

import todo_app

To import a specific function from the module, you would do this:

Syntax:

from file_name import function_name

Command:

from todo_app import todo_list

You can also name the function as you import it:

Syntax:

from file_name import function_name as func

Command:

from todo_app import todo_list as Todo

You could also rename a file when you import it.

Syntax:

import file_name as file

Command:

import todo_app as My_todo

To import all the functions in a module, use an asterisk:

Syntax:

from file_name import *

Command:

from todo_app import *

Conclusion

By the end of this tutorial, you will have learned what functions are, how to define and call a function, arguments and parameters, args and kwargs, and how to use dictionaries and lists in a function.

You could also use tuples in functions. You can go ahead and add tuples to your code. Check out this tutorial for more guidance.