×

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.
So, let’s get some overview of functions in python and define the function and their types.

What is Function in Python?

A function is a collection of related statements that carry out a certain task.

Functions are used to break the program into smaller chunks. A code block runs when the function is called; we can pass parameters into a function. The function returns data known as a result.

Advantages of using a function

  • The program is more readable.
  • Code reusability is there.

Types of Functions

There are two types of function, such as:

  1. Built-in  function
  2. User-define function

Built-in Function

A built-in function in python is a function that is already available in the Python programming language. Examples of built-in functions:

  • max():
syntax: max(agr1, arg2, arg3, .........) or max(itrable)
 # initializing list
nums = [3, 6, 0, 2, 15, 1]
summation = sum(nums)
print(summation)

output:

15 
  • sum():
syntax: sum(arg1, arg2, arg3, ..........) or sum(itrable)


 # initializing list
nums = [4, 7, 9, 5, 0]
summation = sum(nums)
print(summation)

output:

25

User-define Function

We can create our functions; these functions are known as user-defined functions. Let’s understand how to define a function in python.

Defining a Function in Python

In python, a function is defined as the following syntax is given below:-

Syntax

def  function_name(arg1,arg2,arg3,............,argN):
		#function code statements

Let’s see the following parts of the Function:

  • Def keyword: When writing functions, the "def keyword" is used to create a new object and assign it to the function's name.
  • function_name: Uniquely identify the function created by the def keyword.
  • argument(function parameters): in which we can pass data or value to the function.
  • Function code: When the function is called, the indented statements in the function code are executed.

To understand how to define a function in python, let’s take an example is given below:-

#define a function name as fun1().
def fun1():
	print(“javatpoint”)

Here we define a function name as fun1().

Call a Function in Python

Once a function is defined, you can execute it by calling the function. To call the function, use the function name followed by parenthesis ().

Example 1: Let’s understand it by examples given below:-

# define a function name as fun1()
def fun1():
	print(“javatpoint”)
# calling the function fun1()
fun1()

OUTPUT

javatpoint

Example 2:

# define a function name as multNumber()
def multNumber():
	print(5*2)
# calling the function multNumber()
multNumber()

OUTPUT:

10

NOTE: Defining the function should always be present before calling the function. Otherwise, you will get an error.

Let’s take an example to understand this:


# calling the function fun()
fun()
# define a function name as fun()
def fun():
	print("Hello!!Welcome to javatpoint.")

OUTPUT:

NameError: name 'fun' is not defined

Arguments in Function Call

When calling the function, pass an argument or parameter to the function, and put the argument inside parentheses ().

Let’s understand arguments in function by following examples:-

Example 1:

#define a function name as full_name()
def full_name(first_name, surname):
return first_name + " " + surname
#call full_name function by passing arguments in the function
name = full_name("Jayson", "Roy")
print(name)
Output:
Jayson Roy

Example 2:

#define a function name as full_name()
def full_name(first_name, surname):
print( first_name + " " + surname)
#call full_name function by passing arguments in the function
name = full_name("Robin", "Jonas")
print(name)

Output:

Robin Jonas
None

Note: If a function does not have any return value, it returns None by default.

Example 3:

#define a function name as full_name()
def full_name(first_name, surname):
return first_name + " " + surname
#call full_name function by passing arguments in the function
name = full_name("Jayson")
print(name)


TypeError: full_name() missing 1 required positional argument: 'surname'

 In this example, if we don’t pass the whole parameters, we get an error like this.

Types of Arguments

We can call a function by using the following types of arguments:

  • Required argument
  • Keyworded argument
  • Default argument
  • Variable-length arguments

Let’s explain them one by one:

Required Argument

In the required argument, the number of arguments we pass from the function should be the same in both function call and function definition. The order or position of the argument should be the same or followed in both function call and function definition.

Example 1:

#defining power_clac function
def power_calc(base, power):
		ans = 1
		for i in range(power):
			ans *=  base
		return ans
	# calling function without using keyword argument
	ans = power_calc(2, 3)
	print(ans)

Output:

8

Example 2:

# defining addition function
	def addition(num1, num2, num3):
		ans = num1 + num2 + num3
		return ans
	#calling addition function
	summation = addition(5, 8, 2)
	print(summation)

Output:

15

Example 3:

#defining description function
	def description(name, age, gender):
		print("name:", name)
		print("age:", age)
		print("gender:", gender)
	
	description("Robin", 18, "Male")

Output:

name: Robin
age: 18
gender: Male

Keyword Argument

In the keyword argument, the initialization of arguments declared in a function call will match the arguments returned in the function definition based upon the keywords. Or basically, we can say that initialization will be done based on keywords(name), and the order or position is not required here. 

Example 1:

#defining description function
def description(name, age, gender):
               print("name:", name)
               print("age:", age)
               print("gender:", gender)
 description(gender="Male", name="Michel", age=20)

 Output:

name: Michel
age: 20
gender: Male

Example 2:

 # defining power function
 def power_calc(base, power):
               ans = 1
               for i in range(power):
                             ans *= base
               return ans
 # calling function without using keyword argument
 ans1 = power_calc(5, 6)
 print(ans1)
 # calling function using keyword argument
 ans2 = power_calc(power=5, base=6)
print(ans2)

 Output:

15625
7776

Example 3:

 # defining update_list function
 def update(nums, val):
               # initializing a local list
               new_list = []
               for i in nums:
                             new_list.append(i * val)
               return new_list
  
 # initializing list
 nums = [5, 6, 2, 8, 4, 10, 7]
 
 # calling function without keyword argument
 list1 = update(nums, 5)
 print(list1)
 
 # calling function with keyword argument
 list2 = update(val=2, nums=nums)
 print(list2)

 Output:

[25, 30, 10, 40, 20, 50, 35]
[10, 12, 4, 16, 8, 20, 14]

Default Argument

In the default argument, if we call the function without an argument or any argument is not initialized in the function call, then it uses the default value. And the number of arguments need not be the same with both function call and function definition.

Example 1:

 # defining grater_value function
 def grater_value(val1, val2=0):
               if val1 > val2:
                             return val1
               else:
                             return val2
 
 # calling grater_value function with both arguments
 ans1 = grater_value(23, 45)
 print(ans1)
 
 # calling grater_value function passing only one argument
 ans2 = grater_value(23)
 print(ans2)

 Output:

45
23

 Example 2:

 # defining greet function
 def greet(name=""):
               print("hello", name)
  
 # calling greet function with argument
 greet("Justin")
  
 #calling greet function without argument
 greet()

 Output:

hello Justin
hello 

Example 3:

 # defining full_name function
 def full_name(first_name, surname = ""):
               return first_name + " " + surname
  
 # calling full_name function with both arguments
 name1 = full_name("Jack", "Morgan")
 print(name1)
 # calling full_name function with one argument
 name2 = full_name("Michel")
 print(name2)

 Output:

Jack Morgan
 Michel   

Variable-length Argument

In a variable-length argument, it will accept an arbitrary number of arguments. To accept the n number of arguments from the function call in the function definition, we have to replace * as a prefix to the function definition's argument.

Example 1:

#defining summation function
def summation(*vals):
               ans = 0
               for i in vals:
                             ans += i
               return ans
 
# calling summation function
ans = summation(4, 6, 8, 2, 5)
 print(ans)

 Output:

20

 Example 2:

# defining description function
 def description(**vals):
               for key, value in vals.items():
                             print(f"{key}: {value}")
 
 
 description(name="Michel", age=25, gender="Male", balance=20000)

 Output:

name: Michel
age: 25
gender: Male
balance: 20000

Related Topics

AX Contour in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.