Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Python function and its types

Python function types

Python function, function in any programming language is a block of reusable code that performs a specific task, its given name, and can run only when we call it. The function allows us to code reusability, as we can call it any number of times by passing input to the function. The function return value is based on the operation performed on the input value.

In this article, we’ll learn about functions, what are different function types available in Python, and function syntax and demonstrate a few examples of python functions. Let’s get started.

Intro to python Function?

In an application, where we break the code into a smaller chunk that performs a specific task, this is a block of code, which performs the unique task called function. The function allows us code reusability and makes code easier to read.

Python functions are said to be first-class functions, which means we can be assigned to variables, used as arguments to other functions, etc., just like any other object.

A function can take one or more variables as input, carries out some operations using these variables, and produces output in return. You have already used function, as print is a function in Python, and its prints any value that gets passed to it from the console.

#print is function
print('Hello world');

#Output 
Hello world

Python function types

Python has a large number of built-in functions that is ready to use, and the programmer has the ability to create his/her own custom function based on needs. There are three python function types.

  1. Built-in functions: ready-made, function that
  2. User-Defined Functions: Functions that are created by a programmer for his or her own needs.
  3. Anonymous functions are also called lambda functions because they are not declared with the standard-def keyword.
Python function types
Python function types

There are several built-in functions that operate on lists. Here are some useful ones:

Function Description
printFor print output to console
sumReturns the sum of the items in the list
cmp(x, y) Compares two values
lenreturns the number of items in the list
maxreturns the maximum of the items in the list
minreturns the minimum of the items in the list
reversed(seq)Lets you iterate over a sequence in reverse
sorted(seq)returns a sorted list of the elements of seq
tuple(seq)converts a sequence to a tuple
Python built-in function

Let’s demonstrate an example of a python built-in function, we have already seen the print function, let’s use the sum function and this function will find the sum of numbers in a list.

numbers = [10,20,30,40,50];

print(sum(numbers));
//Output 150

How to define a function in python?

We have priveledges to create our own function, and creating custom functions in python is easy. Functions are defined with the keyword def (short for definition), followed by the name of the function. Name of function followed by a pair of parentheses and colon at the end of the parentheses.

Syntax of function

#def functionName(paramter1, paramter2,):
          ... some statement

To call this function, write the name of the function followed by parentheses:

functionName(argument1, argument2,):
def sayHello():
  print ('Hello World from Edupala') # block belonging to the function

# End of function
sayHello() # Call the function

Function Arguments and Local Variable

The function can take input, or we can pass data to the function and we can pass any number of parameters through brackets following the function’s name. Multiple parameters are separated by commas. The parameters have function-level scope. When the function is called we pass an argument to the calling function, where parameters are just copied from the value of arguments.

Let’s demonstrate a custom function to add two numbers,

def sum_number(num1, num2):
    sum = num1 + num2;
    print(f'Sum of two number {num1} and {num2} : {sum}' );
    
sum_number(10, 20);
sum_number(11, 22);
sum_number(10, 23);
sum_number(10, 24);

We can call a function any number of times, as above we had called 4 times with different arguments.

We followed the following steps to define a function in python.

  1. Step 1: Define a function as def sum_number(num1, num2).
  2. Step2: Add two numbers sum = num1 + num2; where num1 and num2 are parameters.
  3. Step 3: Print sum, num1 and num2
  4. Step 4: Call the function by running function name with arguments 10, and 20

The num1 and num2 are parameters we passed inside a function, these values can’t access outside of this function, hence they are local variables and the same as the sum which we used inside the function.

Python supports global variables, and it can access anywhere in the programmer and global variables are defined outside any function. Here is an example of python’s global variable and local variable example.

computer = 90;
def total(english, science, math):
 return (english + science + math + computer);

print(total(70, 80, 90));

Where computer variable is global and all function parameters are local variables.

Python function default value

We can add a default value to a function parameter, if we didn’t send any value in the calling function, then the function can take the default value that we added in the function paramter. Here is an example of it.

#function return multiple value

def subject(english = 60, science = 80, computer =90):
    return english + science + computer;

print(subject(50, 80))

#Output 220

We have set the default value by assigning value to the function parameter, as we have not passed the computer variable value, the function takes the default value when the value is not passed in the function.


 Rules for naming python function

We learn about Function syntax, like all programming, we have certain rules to follow when defining Python functions.

  1. The function name can begin with an alphabetic character, or underscore(_) but the general rules function name starts with a small letter(a-z).
  2. We can’t use the reserved keyword of the python ad function name.
  3. We can’t use special characters like @#$ like inside function name.
  4. The rest of the function name can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).

We can assign a function to another variable

def squareFun(num):
 return num*num;

copiedFun = squareFun
print('squareFun(10) =', squareFun(10), 'copiedFun(10) =', copiedFun(10))

You can define defaults for variables if you want to be able to call the function without passing any variables through at all. You do this by putting an equals sign after the variable name. For example, you can do:


Python function return type

In function can return single or multiple values. A return keyword is used to return values from the function and it indicates that the function should immediately cease execution and return a value to the caller. If there is no return value then the function returns none value or If a return statement is executed without an explicit argument, the none value is automatically returned. Let’s demonstrate a custom function with the return value.

def total(english, science, math):
 return (english + science + math);

print(total(70, 80, 90));

The output of the above function is 240

Python function returns multiple values

Python function can return multiple values, let’s demonstrate two examples.

Python function example
Python function returns multiple values

Example two Python function return value

['English', 'Science', 'Computer']

Anonymous functions

The lambda keyword indicates that what follows will be an anonymous function. Same as normal function, we can pass arguments to the function, followed by a colon and then the function code. The function code
cannot be longer than one line.

sum = lambda a,b: (a+b)	
print (sum(1, 2))	

Recursion

Recursion function, where the function calls itself one or many times during its execution. In many programming like C, we used the factorial of a number to demonstrate its example. Here is a Python recursion example of it, where we are finding a factorial of 5 that 1*2*3*4*5 = 120, and the factorial function calls itself 4 times.

def factorial(num):
	if num==0 or num==1:
		return 1;
	else:
		return num *factorial(num-1)
print(factorial(5));

#output 120

Conclusion
Finally, we have completed the Python function, and function types available in python and also demonstrate a few examples. I hope you liked this tutorial, please consider it sharing with others.

Related Articles

  1. Python String and Methods tutorial
  2. Python variable and its types in details
Python function and its types

Leave a Reply

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

Scroll to top