Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Can we explicitly define datatype in a Python Function?

I have this code where I have explicitly defined the datatype

def add(x, y):\n    z = float ( x ) + float ( y )\n    print "The required Sum is:  {}".format ( z )\n    return z\nadd(5,8)

In Python, variables are never explicitly typed. If we explicitly define datatype in a python function as in above code, does it affect the outcome?


1 Answer
Manogna

In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally. In Java, C++, and other statically-typed languages, you must specify the datatype of the function return value and each function argument.

If we explicitly define datatype in a python function, it still works like a normal program where data type is not declared explicitly.

We get the following output for the given code

C:/Users/TutorialsPoint1/~.py
The required Sum is:  13.0

Consider this function

def addSum(x,y):
       return x+y
print addSum(2.2, 5.6)
print addSum(float(2.2), float(5.6))

OUTPUT

7.8
7.8

So declaration of datatype of a variable explicitly has no impact on the output.



Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.