×

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 setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

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

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python Struct

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.