×

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

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

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

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

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

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.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.