Python: Strong (or Strict) Typing

Read Time:1 Minute, 10 Second

We know about two different data types: numbers and strings. We could, for example, add numbers, because the addition operation is an operation for the type “numbers”.

But what if we applied this operation not to two numbers, but to a number and a string?

print(1 + '7') # TypeError: unsupported operand type(s)...

Python will not allow adding the number 1 and the string ‘7’ because they are different types. You have to first make the string a number or the number a string (we’ll talk about how to do this later). This pedantic attitude towards type compatibility is called strict typing or strong typing. Python is a strongly typed language.

Not all languages do this. PHP, for example, is a language with weak typing. It is aware of the existence of different types (numbers, strings, etc.), but is not very strict about their use, trying to convert information when it seems reasonable. The same applies to JavaScript:

# Number 2 + Line 3 = Line 23
2 + '3' # '23'

Automatic implicit type conversion does seem convenient on the one hand. But in practice this language’s property causes a lot of errors and problems which are hard to find. The code may sometimes work and sometimes not work, depending on whether you have “luck” with automatic conversion in your particular case. The programmer will not notice it at once.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published.

Previous post PHP: Comments
Next post C#: Hello, World!