0

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
asked Apr 29, 2020 at 20:34
4
  • 1
    The base is the number of digit you use to display your number. Binary is a base 2 because it uses 0 and 1, the decimal is base 10 because you use from 0 to 9 Commented Apr 29, 2020 at 20:36
  • A binary number literally means a number expressed in base 2. This is the same as a decimal number is a number expressed in base 10. There is no other base that is appropriate. Commented Apr 29, 2020 at 20:37
  • 1
    Some good reading: en.wikipedia.org/wiki/… Commented Apr 29, 2020 at 20:41
  • 1
    Sounds like you need to learn what binary is. BTW welcome to SO! Check out the tour and How to Ask if you want advice. Commented Apr 29, 2020 at 20:48

2 Answers 2

3

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
answered Apr 29, 2020 at 20:50
Sign up to request clarification or add additional context in comments.

Comments

0

It says what number system your string is in currently. In a binary system, you have only two digits, i.e. 1 and 0. In decimal, you have 10, i.e. 0-9.

See few examples here on Programiz

I hope it clears something!

wjandrea
34k10 gold badges69 silver badges107 bronze badges
answered Apr 29, 2020 at 20:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.