Explicitly define datatype in a Python function
Last Updated :
01 Feb, 2023
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
def add(num1, num2):
print ( "Datatype of num1 is " , type (num1))
print ( "Datatype of num2 is " , type (num2))
return num1 + num2
print (add( 2 , 3 ))
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
def concatenate(num1, num2):
print ( "Datatype of num1 is " , type (num1))
print ( "Datatype of num2 is " , type (num2))
return num1 + num2
print (concatenate( 111 , 100 ))
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...