Explicitly define datatype in a Python function
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
Please Login to comment...