Open In App
Related Articles

Explicitly define datatype in a Python function

Improve Article
Improve
Save Article
Save
Like Article
Like

Unlike other languages Java, C++, etc. Python is a strongly, dynamically-typed language in which we don’t have to specify the data type of the function’s return value and its arguments. It relates types with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions.

Example 1: We have a function to add 2 elements.

Python3




# function definition
def add(num1, num2):
    print("Datatype of num1 is ", type(num1))
    print("Datatype of num2 is ", type(num2))
    return num1 + num2
 
# calling the function without
# explicitly declaring the datatypes
print(add(2, 3))
 
# calling the function by explicitly
# defining the datatypes as float
print(add(float(2), float(3)))

Output:

Datatype of num1 is  <class 'int'>
Datatype of num2 is  <class 'int'>
5
Datatype of num1 is  <class 'float'>
Datatype of num2 is  <class 'float'>
5.0

Example 2: We have a function for string concatenation

Python3




# function definition
def concatenate(num1, num2):
    print("Datatype of num1 is ", type(num1))
    print("Datatype of num2 is ", type(num2))
    return num1 + num2
 
# calling the function without
# explicitly declaring the datatypes
print(concatenate(111, 100))
 
# calling the function by explicitly
# defining the datatypes as string
print(concatenate(str(111), str(100)))

Output:

Datatype of num1 is  <class 'int'>
Datatype of num2 is  <class 'int'>
211
Datatype of num1 is  <class 'str'>
Datatype of num2 is  <class 'str'>
111100

Last Updated : 01 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials