Type conversion in Python

3

When writing some didactic examples in Python 2.7, I came across the following situation in the following program:

a = 0b101
b = 0b111
c = a+b
print c

The result of this program is 12 (decimal). If I want a binary value to be displayed in the sum result, I have to convert the obtained value to binary, and then the program looks like this:

a = 0b101
b = 0b111
c = bin(a+b)
print c

Now, knowing that Python is strongly typed (does not accept automatic type conversion), how, by determining binary values in variables a and b, and summing their values, does it give me a value of the sum as a decimal value? / p>     

asked by anonymous 01.05.2017 / 21:10

1 answer

6

Because the type remains the same. Binary representation and decimal representation are representations of the same type. The value of representing in one way does not mean that the value is another, even less that the type is another. There is no conversion at all.

The bin function does not generate a binary number because technically every number does not of being binary, what this function does is to generate a string with the binary representation of the number, just as if you do not use any function what you will see by default is the decimal representation of a number. But make no mistake you're also seeing a string with the decimal digits, you can not see the number itself.

    
01.05.2017 / 21:17