Python type conversion

Asked

Viewed 1,076 times

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 to display a binary value 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

Well, knowing that Python is strongly typed (does not accept automatic conversion of types), as if, determining binary values in variables a and b, and adding their values, it presents me as the sum value a decimal value?

1 answer

7


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.

The function bin does not generate a binary number, because technically every number is binary, what this function does is generate a binary 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 are not seeing the number itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.