×

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

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python Marshmallow

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.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

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...

6 minutes read.

Python MySQL Client

MySQL client is a project that is the subdivision of the MySQLdb package. This package provides an interface that runs the Python database API. Installing mysqlclient You can easily install mysqlclient with...

5 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.