Functions in Python

Beginners Code Computer Skills Python

Functions in python

A function is a block of code which performs a certain part of the operation for an algorithm. It means when we write a program, we first analyze the algorithm to execute our problem then individually segregate the subproblems. Then we write the code for this individual subproblems and contain them into one individual unit. These individual units are called Functions.

Benefits of writing program using functions:

  • The program becomes structured; hence it will be easy to analyze, debug and test in future use cases.
  • The code becomes reusable. It means we can reuse function code as many times as we want.

Python supports a wide range of inbuilt functions. Due to this vast library of functions, python is often popular as a versatile language. These functions support a wide range of functionalities like building highly responsive web pages to applying functionalities in machine learning.

Defining a function in python

  • To define a function we use def keyword followed by function name and parenthesis.
  • Inside the parenthesis, we pass the parameters to communicate between the different functions.
  • After parenthesis, we provide a colon and continue writing the code from next line ensuring at least one-tab space from the left border of code.

NOTE: Python doesn’t use curly braces to mark the opening and closing of functions. Rather, after the colon mark, it uses one tab space. Modern IDEs implement this feature automatically. You don’t have to worry about that.

Consider this syntax:

def Mario():
      print("I love Mushrooms")
print("I need more coins!")

Note the above example. We have a function called “Mario” and we see two print statements. Here the statement saying “I love mushrooms” belongs to the function. The one saying “I need more coins!” is outside the function, Mario. Hence we conclude that by giving one tab space, we can differentiate whether a part of code belongs to a function or is outside of it.

Function calling in Python

Following all the above rules we can create a function, but it hasn’t been used yet. To use a function, we need to call it outside the function block in the main framework of the program. This is known as function-calling. It has a few sets of rules which you should have in your mind:

  • The function name should be written exactly as it is, including keeping the case intact too.
  • While passing, the number of references should be the same as mentioned in the function.

Consider this example:

def Mario(input):
Mario("I love Mushrooms")
Mario("I need more coins!")

Consider the above example. Here “input” is a variable and it gets its value when the function is called outside its block. It then prints the given input.

Now sending the parameters has two options.

  • Required argument
  • Keyword argument

Required Arguments:

It passes the parameter in their mentioned order of the calling function.

Consider this example:

def Mario(input, word_ct):

Mario("I love Mushrooms", 3)
Mario("I need more coins!", 4)

Here we give the input string and number of words in it to the function. Note that the order is also kept intact as per the initial function definition.

Keyword Arguments:

It passes the parameter in any order. However, we need to assign the values of parameters during passing.

Consider this example:

def Mario(input, word_ct):

Mario(input="I love Mushrooms", word_ct=3)
Mario(word_ct=4, input="I need more coins!")

Here we mention the parameter variables first. Then we assign the values into it. This nullifies the order in which we send the parameter.

NOTE: As long as the names match, the parameters can be sent in any order you wish. But make sure the parameter names are correct, else it would generate an error.

Default Arguments:

Another method exists which is the default argument. Default argument tells it is not compulsory to pass all parameters. But it has some pre-assigned values. Hence no error shows up during execution.

Consider this example:

def Mario(input, word_ct=3):

Mario("I love Mushrooms")
Mario("I need more coins!", 4)

Note the first function call. It sends only input but no word count. However, this doesn’t show any error. The default word count will be printed automatically during execution.

Lambda Functions/ Anonymous Functions

These functions are called Anonymous because they are not declared in standard form i.e. using the def keyword.

Few points to highlight about lambda functions:

  • They can take any number of arguments but they return only one argument as output.
  • Lambda Functions can refer only to those variables present in their parameter list. It means lambda cannot refer to global variables and variables outside its scope.
  • We cannot call a lambda function directly using print function since lambda requires an expression.

In simple words, if we conclude, lambda functions are like standard functions but they don’t have a name and they are written in one line only.


# implementing basic addition operation using lambda
add = lambda var1, var2: var1 + var2
print("Total is", add(10, 20))

Here add is a lambda function. Note that lambda is the keyword used instead of def. There is no such space indentation required in lambda functions. Hence it responds to the function call inside print without any error.

Scope of Variables

Here we can again classify variables depending on where and how they are defined. It primarily determines how a variable behaves in the program. It is of two types:

  • Local variables
  • Global variables

Local variables are defined and used within a function. They are only available for use inside the defining function. It means if any other function tries to call or use that variable inside itself, then it would show an error because for that function the mentioned variable has not been created yet.

This attribute of variables is known as the scope of variables.

However, note that global variables have total access to all functions. They can be used anywhere and in any function.

Consider this example:

# local vs global variables

sum = 0

def add(var1, var2):
    sum = var1 + var2
    print("Sum variable inside add block", sum)

add(10, 20)
print("Sum variable outside add block", sum)

Here we have two variables with the name “sum”. The local variable is used inside the add function which will give result 30 while execution. While the final print statement will give the value of sum as 0 since it is referring to the sum declared initially.