Why the given code worked? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the given code worked?

I learnt that two different types can't be added but in the given case it worked. https://code.sololearn.com/cJ51odcOXsdm/?ref=app

31st Dec 2018, 10:06 AM
Ashutosh Dash
Ashutosh Dash - avatar
7 Answers
+ 4
You can't add objects like strings and numbers (int, float). Adding numbers of different types is no problem (as you can see). The result of any mathematical operation including an int and a float will always be a float: print(5+5.0) # result: 10.0 int+float=float
31st Dec 2018, 10:20 AM
Anna
Anna - avatar
+ 2
Python automatically converts integers to floating point numbers, when used in the same operator.
31st Dec 2018, 10:19 AM
Seb TheS
Seb TheS - avatar
+ 2
Ashutosh Dash Because you can't add numbers and strings. str("4") takes "4", which already is a string because of the quotation marks, and "converts" it to a string. The result will be a string and you'll end up with the attempt to add a float and a string. float(3) + int("4") on the other hand will work.
31st Dec 2018, 10:44 AM
Anna
Anna - avatar
+ 1
Python interpreter implicitly convert your int into a float, because you try adding an integer and a float.
31st Dec 2018, 10:38 AM
Théophile
Théophile - avatar
+ 1
Float and int are numbers, while string are completely different types : characters.
31st Dec 2018, 10:44 AM
Théophile
Théophile - avatar
+ 1
So number + number = OK But number + character = ERROR
31st Dec 2018, 10:45 AM
Théophile
Théophile - avatar
0
Seb TheS Anna Théophile why the same thing didn't happened if i add float and string https://code.sololearn.com/cK5l7LBuHmJA/?ref=app
31st Dec 2018, 10:42 AM
Ashutosh Dash
Ashutosh Dash - avatar