A (seemingly pointless) difference between Python and JavaScript

Coming from JavaScript to Python, I’ve been noticing some differences. I can’t help but compare them as JaveScript is the closest thing to Python I know. Some differences I like, they feel streamlined in comparison. But one thing I’m confused about is when adding a variable to a string.

In JavaScript, it’s rather straightforward:

var number = 1;
var string = "The number is " + number + ".";

string would then be read as “The number is 1.”
JavaScript I guess already knows that when I’m adding a variable to a string, even if it’s not a string itself, that I want that variable to become part of the string. Thus, it automatically converts it.

In Python though, you’d have to do a little bit more.

number = 1
string = "The number is " + str(number) + "."

You have to convert the variable into a string manually. Why couldn’t Python do the same thing in its interpreter? It’s not like you could do that in any other way, so it’s arbitrary. Unless someone can share with me how this rule be in any way helpful? After all, I’m just starting in Python, there might be a good reason for this difference.

1 Like

It’s because Python, unlike JavaScript, is a strongly typed language.

As a result, Python doesn’t try to silently figure out what you want it to do “under the hood” when you give it a confusing operation - like attempting to “add” 1 to a string. Rather, it’s preferable for you to tell it that you want to treat the number as a string - that way we know for sure that when you write + you mean “concatenate” and not “unary addition”.

4 Likes

What javascript does is known as type coercion, and i am glad Python and many other languages don’t do this. JS is actually the odd one out here.

of course there are ways in python to overcome the problem you are facing, like .format().

type coercion can be difficult to understand, and result in weird behavior, to prove my point:

although i read an explanation about this matter, it can be very confusing.

3 Likes

I think I follow what you’re saying. So it takes things more literal so that you have more control and its more cut and dry, did I get that right? I can see how that’s a pro now.

I had no idea JS was the odd one out. It’s the only OOP I’m familiar with so I think you can see how I thought it was the higher standard at first. That comic was great by the way. :laughing:

yes, for example:

console.log("5" + 5);

gives 55. The types are incompatible, but JS tries to make the best of it, resulting in a non-logic mathematical operation.

The original design philosophy was that this created less interruptions in the users browser experience, i don’t think this is true in the long run

due to the code continuing here, another error could be triggered later on in your code, which can make it really difficult to debug properly

3 Likes