I started learning Python recently. I have a problem understanding this:
print(int('0b101', 2))
I understand that it is a binary number that's going to be converted to an integer. But why the base should be 2? and can somebody explain what is the base? Thank you
wjandrea
34k10 gold badges69 silver badges107 bronze badges
2 Answers 2
If no base is given, int defaults to base 10, rather than guessing what base the literal is. For example, 0b101 is also a valid hexadecimal literal:
>>> int('0b101', 16)
45313
>>> int('0xb101', 16)
45313
If you don't want it to be treated as base-10, you have to be explicit about how it should be treated.
>>> int('0b101', 2)
5
Friedrich -- Слава Україні
4,0781 gold badge34 silver badges53 bronze badges
answered Apr 29, 2020 at 20:50
chepner
538k77 gold badges596 silver badges747 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
0and1, the decimal is base 10 because you use from0to9