Skip to content
Related Articles

Related Articles

Explicitly define datatype in a Python function
  • Last Updated : 29 Dec, 2020

Unlike other languages Java, C++, etc. Python is a strongly-typed dynamic language in which we don’t have to specify the data type of the function return value and function argument. It relates type 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 datatype 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 datatype as float
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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :