Just Python Part 6— Functions

A function is a block of code which only runs when it is called. Python function in any programming language is a sequence of statements in a certain order, given a name. When called, those statements are executed. So we don’t have to write the code again and again for each [type of] data that we want to apply it to. This is called code re-usability.

We will study the different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples. As you already know, Python gives you many built-in functions like print, int, float, bin, hex, string, list, set, dictionary, and so.

You can also create your own functions. These functions are called user-defined functions.

Syntax of Function

def func_name( parameters ):
   return [expression]

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses “ ( ) “.
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement — the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Rules for naming python function (identifier)

We follow the same rules when naming a function as we do when naming a variable.

  1. It can begin with either of the following: A-Z, a-z, and underscore(_).
  2. The rest of it can contain either of the following: A-Z, a-z, digits(0–9), and underscore(_).
  3. A reserved keyword may not be chosen as an identifier.

It is good practice to name a Python function according to what it does.

def hello():

You may use a docstring right under the first line of a function declaration. This is a documentation string, and it explains what the function does.

def func1():
This is docstring

You can access this docstring using the __doc__ attribute of the function.

>> func1.__doc__
'\n\tThis is the docstring\n\t'

Calling a Function

To call a function, use the function name followed by parenthesis:

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


If you don’t yet know what to put in the function, then you should put the pass statement in its body. If you leave its body empty, you get an error “Expected an indented block”. You can even reassign a function by defining it again.

>>> def my_function():

>>> my_function()

Python Function Argument

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a function.

From a function’s perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that are sent to the function when it is called.

There are different types of arguments:

  1. Default argument
  2. Keyword argument
  3. Arbitrary argument

Default argument

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −

# Function definition is here
def info( name, age = 35 ):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;# Now you can call info function
info( age=50, name="miki" )
info( name="miki" )

When the above code is executed, it produces the following result −

Name:  miki
Age 50
Name: miki
Age 35

Any number of arguments can have a default value. But you must make sure to not have a non-default argument after a default argument. In other words, if you provide a default argument, all others succeeding it must have default values as well. The reason is simple. Imagine you have a function with two parameters. The first argument has a default value, but the second doesn’t. Now when you call it(if it was allowed), you provide only one argument. The interpreter takes it to be the first argument. What happens to the second argument, then? It has no clue.

def sum(a=1,b):
return a+b

SyntaxError: non-default argument follows default argument
This was all about the default arguments in Python

Keyword Arguments

With keyword arguments in python, we can change the order of passing the arguments without any consequences. Let’s take a function to divide two numbers, and return the quotient.

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

my_function(child2 = "Tobias", child3 = "Linus")def my_function(*kids):
print("The youngest child is " + kids[2])

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

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items accordingly:

def my_function(*kids):
print("The youngest child is {kids}")

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

Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.

This way the function will receive a dictionary of arguments, and can access the items accordingly:

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

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

Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

def my_function(food):
for x in food:

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


Python return statement

A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value. A return statement with no arguments is the same as return None.

def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print("Inside the function : ", total)
return total;

# Now you can call sum function
total = sum( 10, 20 );
print("Outside the function : ", total)

When the above code is executed, it produces the following result −

Inside the function :  30
Outside the function : 30

Scope and Lifetime of Variables in Python

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python

  • Global variables
  • Local variables

Local Scope– A variable that’s declared inside a function has a local scope. In other words, it is local to that function.

def func3():
print(x)>>> func3() #O/P: 7

If you then try to access the variable x outside the function, you cannot.

>>> x

Traceback (most recent call last):

File “<pyshell#96>”, line 1, in <module>


NameError: name ‘x’ is not defined

Global Scope– When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program.

z = 7
def func3():
print(z)>>> func3() #O/P: 7

However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the ‘global’ keyword.

>>> def func4():
global y
print(y)>>> func4() #O/P: 8


A variable’s lifetime is the period of time for which it resides in the memory.

A variable that’s declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable.

>>> def func1():
print(counter)>>> func1() #O/p: 1
>>> func1() #O/p: 1

As you can see here, the function func1() doesn’t print 2 the second time.

Deleting Python function

Till now, we have seen how to delete a variable. Similarly, you can delete a function with the ‘del’ keyword.

>>> del func7
>>> func7()

Python Lambda Expressions

As we said earlier, a function doesn’t need to have a name. A lambda expression in Python allows us to create anonymous python function, and we use the ‘lambda’ keyword for it. The following is the syntax for a lambda expression.

lambda arguments expression

It’s worth noting that it can have any number of arguments, but only one expression. It evaluates the value of that expression, and returns the result. Let’s take an example.

x = lambda a : a + 10

This code takes the numbers 5 as arguments a and put it in the expression (a+10). This makes it 5 + 10 which is 15. Finally, it returns 15.

Actually, the function object is assigned to the identifier myvar.

>>> myvar=lambda a,b:(a*b)+2
>>> myvar(3,5)17

Lambda functions can take any number of arguments:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11)) #Output: 11 * 2 = 22

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Python Recursion Function

In Python function, recursion is when a function calls itself. To see how this could be useful, let’s try calculating the factorial of a number. Mathematically, a number’s factorial is:


To code this, we type the following.

def facto(n):
if n==1:
return 1
return n*facto(n-1)

facto(5) #output is 120

Try recursive functions using the print statements in between the functions to get the clear understanding how recursive functions work.

Conclusion: Python Functions

It is important to revise in order to retain information. In this lesson, we learned about the Python function. First, we saw the different types of functions. Now we can create, update, and delete a function. And we know that a function may take arguments and may return a value. We also looked at the scope and lifetime of a variable. Hope you like the Python Function Tutorial.

Don’t forget to revise the various built-in functions supported by Python. Refer to our tutorials for the same.

Leave a Comment

Your email address will not be published. Required fields are marked *