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:
- Built-in function
- 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