1.

Is Python weakly typed or strongly typed?

Answer»

Depending upon how strict its typing rules are, a programming language is CLASSIFIED as strongly typed or weakly (sometimes CALLED loosely) typed.

Strongly typed language checks the type of a variable before performing an operation on it. If an operation involves incompatible types, compiler/interpreter rejects the operation. In such case, types must be made COMPATIBLE by using appropriate casting techniques.

A weakly typed language does not enforce type safety strictly. If an operation involves two incompatible types, one of them is coerced into other type by performing implicit casts. PHP and JavaScript are the examples of weakly typed languages.

Python is a strongly typed language because it raises TypeError if two incompatible types are involved in an operation

>>> x=10 >>> y='Python' >>> z=x+y Traceback (most recent call last):  File "<pyshell#2>", line 1, in <module>    z=x+y TypeError: unsupported operand type(s) for +: 'int' and 'str'

In above example, attempt to perform addition operation on one integer OBJECT and another string object raises TypeError as neither is implicitly converted to other. If however, the integer object “I” converted to string then concatenation is possible.

>>> x=10 >>> y='Python' >>> z=str(x)+y >>> z '10Python'

In a weakly typed language such as JavaScript, the casting is performed implicitly.

<script> VAR x = 10; var y = "Python"; var z=x+y; document.write(z); </script> Output: 10Python


Discussion

No Comment Found